templatePath = 'template-path/'
angular.module('UCX.Cmis')
.controller 'directiveController',(
  $scope
  $http
  CmisService
  localStorageService
  $timeout
  $uibModal
  ModelService
  Loading
  Utils
  $translate
  $filter
  UploadQueue
  $rootScope
  $location
  ApiService
  $sce
  $injector
  toastr
  $window
  $compile
  SelectMode
  $q
)->

#    if readerPluginVersion >8.1 hide send by email func
  $scope.isIE10=Utils.isIE10()
  $scope.showSendEmail = false
  pluginVersion = CmisService.pluginVersion
  if(parseFloat(pluginVersion)>8.1)
    $scope.showSendEmail = true
  else
    $scope.showSendEmail = false
  if !window.CloudReading
    window.CloudReading={}
  window.CloudReading.Utils =Utils
  $scope.$on('openUploadFilePicker',()->
    console.log('event openUploadFilePicker ')
    $scope.openUploadFilePicker()
  )
  $scope.OS = Utils.getOsName()
  $scope.isIEorEdge = Utils.isIEorEdge()
  $scope.isSafari = Utils.isSafari()
  $scope.isFireFox = Utils.isFireFox()
  $scope.mobileSearchInput={
    keyword:''
  }
  console.log($scope.isFireFox)
  console.log 'iswin',$scope.isIEorEdge
##
#  all Jquery ajax call success or error handle
#
#    As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with the .ajaxSuccess() method, must be attached to document.
#    If $.ajax() or $.ajaxSetup() is called with the 'global' option set to false, the .ajaxSuccess() method will not fire.
#    global (default: true)
#    Type: Boolean
#    Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.
##
  window.recordRequestTime ={
    start:{},
    end:{},
    cost:{}
  }
  $(window).on('blur',()->
    # close dropdowns
    $('.search-area').removeClass('open')
    return true
  )


  $( document ).ajaxSuccess(( event, responseData, settings )->
#    console.log('settings',settings)
#    console.log('ajaxSuccess',responseData)
#    console.log('settings',settings)
#    success but error
    if responseData && responseData.responseJSON && responseData.responseJSON.message
      if responseData.responseJSON.message == 'TOKEN_ERROR'
        Utils.handleTokenError(responseData.responseJSON)
  )
  $( document ).ajaxError(( event, responseData, settings )->
#    console.log('settings',settings)
#    console.log('ajaxError',responseData)
    if responseData && responseData.responseJSON && responseData.responseJSON.message
      if responseData.responseJSON.message == 'TOKEN_ERROR'
        Utils.handleTokenError(responseData.responseJSON)
  )
  $( document ).ajaxSend((event,jqXHR,options)->
#    console.log(event)
#    console.log(jqXHR)
#    console.log(options)
#    console.log("ajaxSend")
    window.recordRequestTime.start[options.url]=Date.now()
  )
  $( document ).ajaxComplete((event,jqXHR,options)->
#    console.log(event)
#    console.log(jqXHR)
    console.log(options)
#    console.log("ajaxComplete")
    window.recordRequestTime.end[options.url]=Date.now()
    cost = window.recordRequestTime.end[options.url]-window.recordRequestTime.start[options.url]
    window.recordRequestTime.cost[options.url] = cost
    if(cost>2000)
      console.warn('cost',cost)
    else
      console.log('cost',cost)
  )

  $scope.firstInit=false
  $scope.docOwner = CmisService.docOwner # 查看其它员工文档
  $scope.templatePath = templatePath
  $scope.messageToMember = $filter('nl2br')(CmisService.messageToMember)
  $scope.showMembers = CmisService.showMembers
  $scope.roomLink = CmisService.roomLink
  $scope.membershipType = CmisService.membershipType
  $scope.supportFile = if typeof File != 'undefined' then true else false
  $scope.multipleChooseFiles = []
  $scope.fileListShow=false
  $scope.pluginUi=CmisService.pluginUi
  $scope.folderOrderBy = Utils.getSort()
  $scope.trStyle = if !$scope.pluginUi then Utils.getFileSort() else true
  $scope.repository = CmisService.repository
  $scope.device = CmisService.device
  $scope.showShareIcon=!CmisService.pluginUi&&CmisService.device!='mobile'&&CmisService.docOwner&&!CmisService.isSharedWithMe
  $scope.project = CmisService.project
  $scope.fromFillAndSign = CmisService.fromFillAndSign
  $scope.isAndroid = CmisService.isAndroid
  $scope.isIOS = CmisService.isIOS
  $scope.filePickerModal=CmisService.filePickerModal
  $scope.lang = Utils.getLanguage()
  $scope.currentUserEmail=CmisService.email
  $translate.use($scope.lang) # fix translate issue PRO-2402
  $(document).on("disconnectErr",(event)->
    Utils.warning($translate.instant('network_err'))
  )
  $scope.fileType=CmisService.fileType
  # 企业云项目的标示
  $scope.isCpdfDoc=CmisService.project=='cpdf360'
  $scope.isSharedWithMe=CmisService.isSharedWithMe
  $scope.fileSelectMode=CmisService.fileSelectMode
  if CmisService.phantomSubscriptionStatus=='true'
    $scope.phantomSubscriptionStatus=true
  else
    $scope.phantomSubscriptionStatus=false

  if CmisService.isEnterpriseSite=='true'
    $scope.isEnterpriseSite=true
  else
    $scope.isEnterpriseSite=false

#  console.log $scope.device

  $scope.changeSort = (sort)->

    if($scope.folderOrderBy == sort)
      if $scope.folderOrderBy.indexOf('-') != -1
        $scope.folderOrderBy = sort.slice(1)
      else
        $scope.folderOrderBy = '-'+sort
    else
      $scope.folderOrderBy = sort
    window.CloudReading.folderOrderBy = $scope.folderOrderBy
    Utils.sendGaEvent('Document list','Sort by:'+$scope.folderOrderBy,$scope.folderOrderBy)
    localStorageService.set "folder-order-by" , $scope.folderOrderBy

  $scope.changeDocShowStyle=()->
    $scope.trStyle=!$scope.trStyle
    Utils.sendGaEvent('Document list','List style:'+$scope.trStyle,'List style or thumbnail style')
    localStorageService.set "file-order-by" , $scope.trStyle
    window.CloudReading.trStyle = $scope.trStyle
  window.CloudReading.changeDocShowStyle = $scope.changeDocShowStyle
  window.CloudReading.changeSort = $scope.changeSort
  window.CloudReading.trStyle = $scope.trStyle
  window.CloudReading.folderOrderBy = $scope.folderOrderBy
  $scope.translateErrorMsg=Utils.translateErrorMsg


  CmisServiceSession = CmisService.session

  cancalCheckoutUploadNewversion = () ->
    console.log $scope.tempFile
    console.log $scope.tempFile.isVersionSeriesCheckedOut
    console.log Utils.isUploadNewVersioning
    if Utils.isUploadNewVersioning
      localStorageService.set "cancel-file-checkout" , $scope.tempFile.id

  window.onbeforeunload = (e) ->
    if Utils.isUploadNewVersioning == true
      cancalCheckoutUploadNewversion()
      return ''

#  $scope.$on(
#    '$locationChangeSuccess',
#    (e, newUrl, oldUrl)->
#      if $scope.progress != 100
#        return
#      if newUrl.substr(newUrl.lastIndexOf('#')) == -1
#        return
#      anchor = newUrl.substr(newUrl.lastIndexOf('#')+1)
#      if anchor.indexOf('file') == -1 && anchor.indexOf('search') == -1
#        localStorageService.set "lastAnchor" , anchor
#      $scope.doActionFromAnchor(anchor)
#  )
  $scope.$on(
    '$locationChangeSuccess',
    (e, newUrl, oldUrl)->
      if CmisService.isAndroid || CmisService.isIOS
        localStorageService.set "lastAnchor" , anchor
        return
      #      这个 地方的return 需要修改啊 不能这样 要等 progress == 100 之后再去 监听 url 变化
      if $scope.progress != 100
        return
      if newUrl.lastIndexOf('#') == -1
        if $scope.tree[0]
          console.log('oyeah')
          anchor = '/folder/'+$scope.tree[0]['id']
          $scope.doActionFromAnchor(anchor)
          return
        else
          console.log('ggggg')
          return
      anchor = newUrl.substr(newUrl.lastIndexOf('#')+1)
      if anchor.indexOf('file') ==-1 && anchor.indexOf('search') ==-1
        localStorageService.set "lastAnchor" , anchor
      $scope.doActionFromAnchor(anchor)
  )
  $scope.$on('context-menu-opening',(event, args)->
    console.log('context-menu-opening')
  )
  $scope.$on('context-menu-closed',(event, args)->
    console.log('context-menu-closed')
  )

  $scope.menuOptions=(file)->
    console.log(file)
    maintainContextMenu=true
    _this=$scope
    if file && file.id && $scope.multipleChooseFilesId.indexOf(file.id)==-1
      $scope.chooseFile(file,null,null,maintainContextMenu)
    if $scope.multipleChooseFiles.length == 0 || !file
      # 公共菜单
      if($scope.filePickerModal!='retire')
        return [
          {
            html: '<a ng-click="createFolder()"><i class="icon icon-folder-open"></i> {{"create_folder" | translate}}</a>'
            compile: true
            displayed: $scope.currentFolder.allowableActions.canCreateFolder
          }
          {
            html:'<a ng-click="setFileCDRMPerm(null,true)"><i class="icon icon-up"></i> {{"upload_file" | translate }}</a>'
            compile: true
            displayed: $scope.currentFolder.allowableActions.canCreateDocument && $scope.supportFile
          }
        ]
      else
        return null

    if $scope.multipleChooseFiles.length==1
      if $scope.multipleChooseFiles[0].isDocument()
        file=$scope.multipleChooseFiles[0]
        if $scope.currentFolder.isReadonly()
          return [
            {
              html:'<a class="popup-left-border" ng-class="{\'style-disable\':!file.canPreview(),\'\':file.canPreview()}" ng-click="preview(file,$event)"><i class="icon icon-eye"></i><span> {{\'preview\' | translate }}</span></a>'
              compile: true
              displayed: file.allowableActions.canGetContentStream && $scope.filePickerModal!='retire'
            }
          ]
        else
          return [
            {
              html:'<a class="popup-left-border" ng-click="preview(file,$event)"><i class="icon icon-eye"></i><span> {{\'preview\' | translate }}</span></a>'
              compile: true
              enabled: file.canPreview()
              displayed: file.allowableActions.canGetContentStream && $scope.filePickerModal!='retire'
            }
            {
              html:'<a class="popup-left-border" ng-click="setFileCDRMPerm(file,false)"><i class="icon icon-protect"></i><span> {{\'权限修改\' | translate }}</span></a>'
              compile: true
              displayed: !$scope.isSharedWithMe && $scope.docOwner && $scope.currentFolder.isCDRMFolder() && $scope.project=='cpdf360'
            }
            {
              html:'<span class="cloud-reading-share" file="file" current-scope="_this"></span><a href="javascript:;" style="position: relative;z-index:0;"><i class="icon icon-external-link"></i><span> {{\'share_file\' | translate }}</span></a>'
              compile: true
              displayed: !$scope.isSharedWithMe && $scope.filePickerModal!='retire'
            }
            {
              html:'<a class="popup-left-border"><i class="icon icon-convert"></i> <span>{{\'convert\' | translate }}</span><span class="pull-right" style="line-height: 24px;"><i class="fa fa-caret-right"></i></span></a>'
              compile: true
              displayed: $scope.phantomSubscriptionStatus && !$scope.isEnterpriseSite && file.contentStreamMimeType=='application/pdf'
              children: ()->
                return [
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'PDFTOWORD\',file)">{{ \'pdf2word\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'PDFTOEXCEL\',file)">{{ \'pdf2excel\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'PDFTOPPT\',file)">{{ \'pdf2ppt\' | translate }}</a>'
                    compile: true
                  }
                  null
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'PDFTOIMG\',file)">{{ \'pdf2img\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'PDFTOTXT\',file)">{{ \'pdf2txt\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'PDFTOHTML\',file)">{{ \'pdf2html\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'PDFTOCPDF\',file)">{{ \'pdf2cPdf\' | translate }}</a>'
                    compile: true
                  }
                  null
                  {
                    html:'<a class="popup-left-border" ng-click="convertPdfTo(\'EXPORTALLIMG\',file)">{{ \'export_all_image\' | translate }}</a>'
                    compile: true
                  }
                ]
            }
            {
              html:' <a class="popup-left-border" ng-click="compress_PDF(\'OPTIMIZER\',file)" hover-dropdown-toggle><i class="icon icon-compress"></i><span> {{\'compress_PDF\' | translate }}</span></a>'
              compile: true
              displayed: $scope.phantomSubscriptionStatus && !$scope.isEnterpriseSite && file.contentStreamMimeType=='application/pdf'
            }
            {
              html:'<a class="popup-left-border"><i class="icon icon-organizer"></i> <span>{{\'organize\' | translate }}</span><span class="pull-right" style="line-height: 24px;"><i class="fa fa-caret-right"></i></span></a>'
              compile: true
              displayed: $scope.phantomSubscriptionStatus && !$scope.isEnterpriseSite && file.contentStreamMimeType=='application/pdf'
              children: ()->
                return [
                  {
                    html:'<a class="popup-left-border" ng-click="organizePDF(\'MERGEPDF\',file)">{{ \'merge_PDF\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="organizePDF(\'SPLITPDF\',file)">{{ \'split_PDF\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="organizePDF(\'PAGEORGANIZER\',file)">{{ \'organize_PDF\' | translate }}</a>'
                    compile: true
                  }
                  null
                  {
                    html:'<a class="popup-left-border" ng-click="organizePDF(\'WATERMARK\',file)">{{ \'add_watermark\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="organizePDF(\'PDFHEADERFOOTER\',file)">{{ \'add_header_footer\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="organizePDF(\'PDFFLATTEN\',file)">{{ \'flatten_PDF\' | translate }}</a>'
                    compile: true
                  }
                ]
            }
            {
              html:'<a class="popup-left-border" hover-dropdown-toggle><i class="icon icon-protect"></i><span> {{\'protect\' | translate }}</span><span class="pull-right" style="line-height: 24px;"><i class="fa fa-caret-right"></i></span></a>'
              compile: true
              displayed: $scope.phantomSubscriptionStatus && !$scope.isEnterpriseSite && file.contentStreamMimeType=='application/pdf'
              children: ()->
                return [
                  {
                    html:'<a class="popup-left-border" ng-click="protectPdf(\'PDFPROTECT\',file)">{{ \'password_protect\' | translate }}</a>'
                    compile: true
                  }
                  {
                    html:'<a class="popup-left-border" ng-click="protectPdf(\'PDFREDACTOR\',file)">{{ \'redact_PDF\' | translate }}</a>'
                    compile: true
                  }
                ]
            }
            {
              html:'<a class="popup-left-border" ng-click="moveTo(file)"><i class="icon icon-move-file"></i> {{ \'move_to\' | translate }}</a>'
              compile: true
              displayed: !$scope.searchModeIsOn && file.allowableActions.canMoveObject && $scope.filePickerModal!='retire'
            }
            {
              html:'<a class="popup-left-border" ng-click="moveToPrivateFolder(file,$event)"><i class="icon icon-move-file"></i> {{ \'make_private\' | translate }}</a>'
              compile: true
              displayed: !$scope.searchModeIsOn && file.allowableActions.canMoveObject && $scope.currentFolder.isCDRMFolder() && !$scope.isSharedWithMe && !$scope.currentFolder.isPrivateFolder()
            }
            {
              html:'<a ng-click="sendViaEmail(file)"><i class="fa fa-envelope-o"></i><span> {{\'send_via_email\' | translate }}</span></a>'
              compile: true
              displayed: file.isDocument() && $scope.repository == 'fxcld' && $scope.device=='foxitReader' && $scope.showSendEmail && $scope.filePickerModal!='retire'
            }
            {
              html:'<a class="popup-left-border" ng-click="download(file)"><i class="icon icon-down"></i><span> {{\'download\' | translate }}</span></a>'
              compile: true
              displayed: $scope.isSharedWithMe && file.allowableActions.canGetContentStream && ($scope.device != 'foxitReader' || $scope.isIEorEdge) && !$scope.isSafari && file.description && file.description.canDownload==1
            }
            {
              html:'<a class="popup-left-border" ng-click="download(file)"><i class="icon icon-down"></i><span> {{\'download\' | translate }}</span></a>'
              compile: true
              displayed: !$scope.isSharedWithMe && file.allowableActions.canGetContentStream && !$scope.isSafari
            }
            {
              html:' <a ng-click="showDetail()"><i class="icon icon-info"></i><span> {{\'view_detail\' | translate }}</span></a>'
              compile: true
              displayed: !$scope.detailPanelIsShow
            }
            {
              html:'<a class="popup-left-border" ng-click="rename(file)"><i class="icon icon-edit" ></i><span> {{ \'rename\' | translate }}</span></a>'
              compile: true
              displayed: file.allowableActions.canUpdateProperties && $scope.filePickerModal!='retire'
            }
            {
              html:'<a class="popup-left-border" ng-click="openModifyFilePicker(file)"><i class="icon icon-up" ></i><span> {{ \'upload_new_version\' | translate }}</span></a>'
              compile: true
              displayed: file.allowableActions.canUpdateProperties && $scope.project!='cpdf360' && $scope.filePickerModal!='retire'
            }
            {
              html:'<a class="popup-left-border" ng-click="delete(file)"><i class="icon icon-delete"></i><span> {{\'delete\' | translate }}</span></a>'
              compile: true
              hasTopDivider: true
              displayed: file.allowableActions.canDeleteObject
            }
            {
              html:'<a ng-click="fillAndSign(file)"><i class="fa fa-link"></i> <span>fill and sign {{ fillAndSign }}</span></a>'
              compile: true
              displayed: $scope.filePickerModal!='retire' && $scope.fromFillAndSign
            }
            {
              html:'<a ><span> {{ "高级编辑" | translate }}</span></a>'
              compile: true
              hasTopDivider: true
              enabled: false
              displayed: $scope.project=='cpdf360'
            }
            {
              html:'<a ><span> {{ "国密签章" | translate }}</span></a>'
              compile: true
              enabled: false
              displayed: $scope.project=='cpdf360'
            }
            {
              html:'<a ><span> {{ "互联表单" | translate }}</span></a>'
              compile: true
              enabled: false
              displayed: $scope.project=='cpdf360'
            }
            {
              html:'<a ><span> {{ "工作流" | translate }}</span></a>'
              compile: true
              enabled: false
              displayed: $scope.project=='cpdf360'
            }
          ]
      else
        # folder
        file=$scope.multipleChooseFiles[0]
        return  [
          {
            html:'<a class="popup-left-border" ng-click="moveTo(file)"><i class="icon icon-move-file"></i><span> {{ \'move_to\' | translate }}</span></a>'
            compile: true
            displayed: file.allowableActions.canUpdateProperties && !file.readOnly && $scope.filePickerModal!='retire'
          }
          {
            html:'<a class="popup-left-border" ng-click="rename(file)"><i class="icon icon-edit" ></i><span> {{ \'rename\' | translate }}</span></a>'
            compile: true
            displayed: file.allowableActions.canUpdateProperties && !file.readOnly
          }
          {
            html:'<a class="popup-left-border" ng-click="deleteFolder(file, null,true,true)"><i class="icon icon-delete"></i><span> {{\'delete\' | translate }}</span></a>'
            compile: true
            displayed: !file.isRoot() && !file.isDocument() && file.allowableActions.canDeleteObject && !file.readOnly
          }
          {
            html:'<a ng-click="showDetail()"><i class="icon icon-info"></i><span> {{\'view_detail\' | translate }}</span></a>'
            compile: true
            displayed: !$scope.detailPanelIsShow
          }
        ]
    if $scope.multipleChooseFiles.length>1
      return [
        {
          html:'<a class="popup-left-border" ng-mousedown="moveTo(multipleChooseFiles,$event)"><i class="icon icon-move-file"></i><span> {{ \'move_to\' | translate }}</span></a>'
          compile: true
          displayed: !$scope.searchModeIsOn && $scope.canMoveMultipleFiles
        }
        {
          html:'<a class="popup-left-border" ng-mousedown="multipleDownload()"><i class="icon icon-down"></i><span> {{\'download\' | translate }}</span></a>'
          compile: true
          displayed: !$scope.searchModeIsOn && $scope.canMoveMultipleFiles
        }
        {
          html:'<a class="popup-left-border" ng-mousedown="multipleDel($event)"><i class="icon icon-delete"></i><span> {{\'delete\' | translate }}</span></a>'
          compile: true
          displayed: !$scope.searchModeIsOn && $scope.canMoveMultipleFiles
        }
        {
          html:'<a class="popup-left-border" ng-mousedown="mergePdf(multipleChooseFiles,$event)"><i class="icon icon-merge"></i><span> {{\'merge_pdf\' | translate }}</span></a>'
          compile: true
          enabled: $scope.disableMerge
          displayed: $scope.phantomSubscriptionStatus && !$scope.isEnterpriseSite && !$scope.canMerge($scope.multipleChooseFiles)
        }
      ]
  #    [[
  #      ($itemScope) ->
  #        console.log($itemScope)
  ##        $itemScope.item.name
  #      ($itemScope) ->
  #        # Action
  #        return
  #    ]]
  $scope.canMerge = (multipleFiles)->
    canMerge = false
    for file in multipleFiles
      if file.canPreviewLikePdf()
        canMerge = true
      else
        canMerge = false
        break
#    console.log('========can merge=======')
#    console.log(canMerge)
    return canMerge
  $scope.mobileShowInfo=false
  $scope.goToParentFolder =()->
    if($scope.currentFolder['name']=='search_result')
      $scope.cancelSearch()
      return false
    parentFolder = $scope.currentFolder.getParent()
    $scope.dbClick(parentFolder)
  $scope.showInfo = (file,e)->
#    if CmisService.device=='mobile'
#      if ContextMenuService.menuElement
#        console.log(ContextMenuService.menuElement)
#        ContextMenuService.close(ContextMenuService.menuElement)
#      else
#        $scope.showContextmenu(file.id)
#      return true
    if e
      e.stopPropagation()
      e.preventDefault()
    $scope.choseFile=file
    if !file.renditions
      file.getRenditions(()->
        $timeout(()->
          $scope.$apply()
        )
      ,null,true)
    console.log('====file====')
    console.log(file)
    file.loadingAce=true
    file.getAces((data)->
      # success
      file.loadingAce=false

      $timeout(()->
        $scope.$apply()
      )
    ,(data)->
      # error
      file.loadingAce=false
      $timeout(()->
        $scope.$apply()
      )
    ,true)
    $scope.firstInit=true
    $scope.mobileShowInfo=true
    return false
  $scope.closeOptionsPanel=(callbackFn)->
    $scope.mobileShowOptionsPanel=false
    $scope.mobileShowToolsPanel=false
    $timeout(()->
      $scope.showMobileMask=false
      $scope.commonOptions=false
      $scope.fileOptions=false
      $scope.showBigQrcode=false
      $scope.closePanelInPanel()
      if callbackFn
        callbackFn()

    ,100)
    true
  $scope.showCommonOptions = (file,e)->
    $scope.choseFile=file
    $scope.showMobileMask=true
    $scope.mobileShowOptionsPanel=true
    $scope.commonOptions=true
    $scope.firstInit=true
    console.log('=====qqqqq')
    return false
  $scope.showFileOptions=(file,e)->
    $scope.choseFile=file
    $scope.multipleChooseFiles=[]
    $scope.multipleChooseFiles.push(file)
    window.CloudReading.choseFile=$scope.choseFile
    window.CloudReading.multipleChooseFiles = $scope.multipleChooseFiles
    if e
      e.stopPropagation()
    $scope.closeMobileSearchBar()
    $scope.firstInit=true
    $scope.showMobileMask=true
    $scope.mobileShowOptionsPanel=true
    $scope.fileOptions=true

  $scope.showPanelInPanel=(toolsCate,e)->
    if e
      e.stopPropagation()
    console.log(toolsCate)
    $scope.compressPanel=false
    $scope.protectPanel=false
    $scope.organizePanel=false
    $scope.convertPanel=false
    $scope.sharePanel=false
    if toolsCate=='compress'
      $scope.compressPanel=true
    else if toolsCate=='protect'
      $scope.protectPanel=true
    else if toolsCate=='organize'
      $scope.organizePanel=true
    else if toolsCate=='convert'
      $scope.convertPanel=true
    else if toolsCate=='share'
      $scope.sharePanel=true
    $scope.showMobileMask=true
    $scope.commonOptions=false
    $scope.fileOptions=false
    $scope.mobileShowOptionsPanel=false

    $scope.mobileShowToolsPanel=true
  $scope.closePanelInPanel=()->
    $scope.mobileShowToolsPanel=false
    $scope.compressPanel=false
    $scope.protectPanel=false
    $scope.organizePanel=false
    $scope.convertPanel=false
    $scope.showMobileMask=false
  $scope.backToPreviewOptions=()->
    $scope.mobileShowToolsPanel=false
    $scope.compressPanel=false
    $scope.protectPanel=false
    $scope.organizePanel=false
    $scope.convertPanel=false
    $timeout(()->
      $scope.showFileOptions($scope.choseFile)
    ,100)
  $scope.mobileShare=(cmisFileObj,e)->
    e && e.stopPropagation()
    $scope.publicShare=false
    if cmisFileObj.sharedLink
      $scope.sharedUser=[]
      for ace in cmisFileObj.aces
        console.log(ace)
        if ace.userId!=CmisService.email && ace.userId!='everyone' && ace.userId!='guest'
          if $scope.sharedUser.indexOf(ace.userId)==-1
            $scope.sharedUser.push(ace.userId)
      for ace in cmisFileObj.aces
        if ace.userId=='guest' && ace.permission=='cmis:read'
          $scope.publicShare=true


      $timeout(
        $scope.showPanelInPanel('share')
      ,1400)
    else
      $scope.closeOptionsPanel()
      Utils.showLoading()
      $scope.publicShare=true
      ApiService.setSharedInfo(cmisFileObj,[{"guest":"cmis:read"}],'',true,(data)->
        Utils.closeLoading()
        console.log(data)
        if(data.data && data.data.failed_share)
          if data.data.failed_share.length>0
            str=''
            for userName in data.data.failed_share
              str=userName+' '
          Utils.warning('Fail to share to '+str+'')

        data.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
        data.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
        newFile = ModelService.createDocument(data.data.cmis_document)
        console.log('====newFile')
        console.log(newFile)
        cmisFileObj.description = newFile.description
        cmisFileObj.sharedLink = newFile.sharedLink
        $scope.choseFile = cmisFileObj
        $scope.showPanelInPanel('share')
        $timeout(()->
          $scope.$apply()
        ,0)

      ,(err)->
        Utils.closeLoading()
        console.log(err)
      )
  successSetShareInfoCallback = (data,file)->
    if(data.data && data.data.failed_share)
      if data.data.failed_share.length>0
        str=''
        for userName in data.data.failed_share
          str=userName+' '
      Utils.warning('Fail to share to '+str+'')

    data.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
    data.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
    newFile = ModelService.createDocument(data.data.cmis_document)
    file.description = newFile.description
    file.sharedLink = newFile.sharedLink
    callback = (cmisData)->
      if cmisData
        data=cmisData
        cmisData.data.cmis_document['succinctProperties'] =data.data.cmis_document['properties']
        cmisData.data.cmis_document.acl['aces'] = Utils.formatAcl(data.data.cmis_document.acl)
        newFile = ModelService.createDocument(cmisData.data.cmis_document)
        file.description = newFile.description
        file.aces = newFile.aces
        file.disableDownload = newFile.disableDownload
      if window.FX && window.FX.app && window.FX.app.sendMessage
        window.FX.app.sendMessage({
          type:'cmisData',
          data:data
        })
      $timeout(()->
        $scope.$apply()
      )
      # ga and
      Utils.sendGaEvent('Share setting','Save Changes','')
      Utils.success($translate.instant('set_share_suc'))
      $scope.stopSharing=false

   
    callback()


  $scope.stopShare=(file)->
    if !file
      file=$scope.choseFile
    $scope.stopSharing=true
    ApiService.stopShare(file.id,(data)->
      $scope.stopSharing=false
      successSetShareInfoCallback(data,file)
      $scope.closePanelInPanel()
    ,(err)->
      $scope.stopSharing=false
      Utils.warning(err)
      $scope.closePanelInPanel()
      $timeout(()->
        $scope.$apply()
      )
    )
  appSharedLink = {
    google:'https://plus.google.com/share?url='
    facebook:'https://www.facebook.com/share.php?u='
    twitter:'https://twitter.com/intent/tweet?text='
    linkedin:'https://www.linkedin.com/shareArticle?mini=true&url='
    weibo:'http://service.weibo.com/share/share.php?title='

  }
  $scope.getAppSharedApiLink = (appName)->
    link=''
    if appName=='weibo'
      link=appSharedLink[appName]+encodeURIComponent($scope.choseFile.name)+' '
    else
      link=appSharedLink[appName]
    link

  $scope.shareTo = (appName,e)->
    $scope.closePanelInPanel()
    if window.FX && window.FX.app && window.FX.app.sendEmail
      if e
        e.stopPropagation()
        e.preventDefault()
      window.FX.app.sendMessage({
        type:'shareTo',
        appName:appName
      })
      return false
    if appName == 'email'
      e && e.stopPropagation()
      if window.top
        window.top.location.href='mailto:?body='+$scope.choseFile.sharedLink+'&subject='+$scope.choseFile.name
      else
        window.location.href='mailto:?body='+$scope.choseFile.sharedLink+'&subject='+$scope.choseFile.name
      return true
    appSharedApiLink = $scope.getAppSharedApiLink(appName)
    if CmisService.device == 'platform-pad'
      cordova.InAppBrowser.open(appSharedApiLink+$scope.fileLink, '_blank', 'hidden=no')
    else
      if CmisService.device != 'mobile'
        top = (window.screen.height-365)/2
        left = (window.screen.width-650)/2
      else
        top = 0
        left = 0
      window.open(
        appSharedApiLink+encodeURIComponent($scope.choseFile.sharedLink)
        appName
        "width=650,height=365,left="+left+",top="+top+",resizable,scrollbars=yes,status=1"
      )
    Utils.sendGaEvent('Share setting','Social share',appName)
    return true
  $scope.generateBigQrcode = ()->
    qrcodeHtml = $compile('<span qrcode width="180" height="180" url="'+$scope.choseFile.sharedLink+'"></span>')($scope)
    $scope.qrcodeHtml = $(qrcodeHtml[0]).html()
    #  $scope.qrcodeHtml = $sce.trustAsHtml('<b style="color: red">I can</b> have <div class="label label-success">HTML</div> content');
    #  $scope.qrcodeHtml = $sce.trustAsHtml(qrcodeHtml.html())
    $timeout(()->
      $('#qrcode').empty().append(qrcodeHtml[0])
    )
    $timeout(()->
      tinyQrcodeEle = $window.document.querySelector('#qrElement')
      #    bigQrcodeEle = $window.document.querySelector('#popover-qrcode')
      #    tinyQrcode={}
      #    bigQrcode={}
      #    bigQrcode.position = $uibPosition.position(bigQrcodeEle)
      #    tinyQrcode.position = $uibPosition.position(tinyQrcodeEle)
      #    console.log(tinyQrcode.position)
      #    console.log(bigQrcode.position)
      #  120 qrcode width 14 padding 2 border
      #    $scope.styles = {
      #      top:tinyQrcode.position.height+'px'
      #      left:tinyQrcode.position.left-Math.abs(120+14*2+4-tinyQrcode.position.width)/2+'px'
      #    }
      $scope.styles = {
        top:48+'px'
        left:177+'px'
      }
#    console.log($scope.elemVals.position)
    ,300)
  $scope.showBigQrcode = false
  $scope.hideQrcode = ()->
    $scope.showBigQrcode=false
    $scope.closePanelInPanel()
  $scope.showQrcode = ()->
    $scope.closePanelInPanel()
    $scope.generateBigQrcode()
    $scope.showMobileMask=true
    $scope.showBigQrcode=true
  $scope.copyOnSuccess = (e)->
    console.log('====copy succ')
    console.info('Action:', e.action)
    console.info('Text:', e.text)
    console.info('Trigger:', e.trigger)
#    e.clearSelection()
    $timeout(()->
      $scope.copy_status = $translate.instant('Copied')
      $scope.tooltipIsOpen = true
    )
    $timeout(()->
      $scope.tooltipIsOpen = false
    ,3000)
    Utils.sendGaEvent('Share setting','Copy link',$scope.fileLink)

  $scope.copyOnError = (e)->
    console.log('====copy failed')
    console.error('Action:', e.action)
    console.error('Trigger:', e.trigger)
    $timeout(()->
      $scope.copy_status = 'copy_failed'
      $scope.tooltipIsOpen = true
    )
    $timeout(()->
      $scope.tooltipIsOpen = false
    ,3000)
  $scope.showMobileSearchBar=(e)->
    if e
      e.stopPropagation()
    $scope.closeOptionsPanel(()->
      $scope.showSearchBar=true
      $scope.showMobileMask=true
    )
  $scope.closeMobileSearchBar=()->
    $scope.showSearchBar=false
    $scope.showMobileMask=false
  $scope.mobileSearch=(e)->
    title=$scope.mobileSearchInput.keyword
    if title
      if Utils.sqlContainIllegalChar(title)
        $translate('contain_illegal_char').then((result)->
          Utils.warning(result)
        )
        return
    if e
      if e.key=='Enter' || e.keyCode==13
        $scope.showMobileMask=true
        $scope.search(null,null,'type=all&title='+title)
        $scope.searchModeIsOn=true
  $scope.searchBarCancelBtnFn=()->
    $scope.cancelSearch()
    $scope.closeMobileSearchBar()
  $scope.clearSearchInput=()->
    $scope.searchKeyword=''

  $scope.toggleAddOptions=()->
    $scope.isAddOptionsShow=!$scope.isAddOptionsShow
    $scope.firstInit=true
  $scope.closeAddOptions=()->
    $scope.isAddOptionsShow=false
  $scope.mobileCreateFolder=()->
    $scope.closeAddOptions()
    $scope.createFolder()
  $scope.mobileUploadFile=()->
    $scope.closeAddOptions()
    $scope.openUploadFilePicker($scope.currentFolder)

  $scope.sortBy=(listBy)->
    $scope.changeSort(listBy)
  $scope.closeInfo = ()->
    $scope.mobileShowInfo=false
  $scope.mergePdf = (multipleFiles,event)->
    
    if event
      event.preventDefault()
      event.stopPropagation()
    if $scope.disableMerge
      Utils.warning($translate.instant('merge_not_support_for_too_many'))
      return
    else
      if window.mergePdf
        Utils.sendGaEvent('PDF','Merge','')
        $scope.noNeedClearSelection=true
#        if(ContextMenuService.menuElement)
#          ContextMenuService.close(ContextMenuService.menuElement)
        window.mergePdf()
      return
  $scope.organizePDFPage = (file)->
#    link = '&fileurl[]='+encodeURIComponent(file.getPreviewLink())+'&filename[]='+encodeURIComponent(file.name)
#    targetUrl = CmisService.cwebToolsApi+'?al=en-US&mode=phantom-page-organizer&access_token='+CmisService.token+link

    token = CmisService.token
    domain = CmisService.baseUrl.replace('cloud', 'pdfeditor') # https://pdfeditor-demo.connectedpdf.com/
    doc_preview_url = "/preview/cmis/"+file.id+"/"+encodeURIComponent("&viewermodel=1") # PPO mode
    targetUrl = domain+"login-integration/"+encodeURIComponent(doc_preview_url)+"/"+token

    console.log('========targetUrl =======')
    console.log(targetUrl)

    if window.organizePDFPage
      Utils.sendGaEvent('Organizer','Page','')
      window.organizePDFPage(file)
      return
    if CmisService.device == 'phantom-online' || CmisService.device == 'reader-online'
      window.parent.angularHeaderComponent.zone.run(()->
        window.parent.angularHeaderComponent.navigateByUrl(doc_preview_url)
      )
      return true;

    window.open(targetUrl)
    return true


  $scope.pdfPreview = (document)->
    if CmisService.isIOS
      $cordovaStatusbar = $injector.get('$cordovaStatusbar')
      $cordovaStatusbar.hide()
    $scope.iframePdf = true
    $scope.isOdfPreview=false
    $scope.isFullScreenPreview = false
    $scope.isNormalFilePreview=true
    url = CmisService.baseUrl+'doc/pdf-preview?objectid='+document.id + '&token=' + CmisService.token
    $http.get(CmisService.baseUrl + 'api/document/get-doc-preview-page?object_id=' + document.id + '&access-token='+CmisService.token+'&t='+(new Date()).valueOf())
    .success (data)->
      page = 1
      if data.page_number
        page = data.page_number
      url = url+'#page=' + page
      $scope.previewUrl = $sce.trustAsResourceUrl(url)
    .error (error)->
      $scope.previewUrl = $sce.trustAsResourceUrl(url)

  $scope.preview = (document)->
    if $scope.filePickerModal=='retire'
      return false
    if !document.isDocument()
      return false
    if !$scope.docOwner
      # current user has read permission
      cmisId=document.id
      if decodeURIComponent(document.id).indexOf(',')>-1
        cmisId=document.id
      else
        cmisId=document.id+','+document.versionLabel
      ApiService.getCDocInfoByCmisId(cmisId).then((resolveData)->
        console.log(resolveData)
        canPreview=false
        if resolveData.ret==0 && resolveData.data && resolveData.data.acl && resolveData.data.acl.length>0
          for user in resolveData.data.acl
            if user.isRevoke==0
              if user.userAttribute && user.userAttribute.userEmail
                if CmisService.email==user.userAttribute.userEmail
                  canPreview=true
          console.log('==== canPreview',canPreview)
          if canPreview
            lang=localStorageService.get('language')
            lang=Utils.getFullLang(lang)
            previewUrl = window.cReaderUrl+'/pdf-preview/pdf-viewer?cmisId='+cmisId+'&fileName='+document.name+'&al='+lang
            window.open(previewUrl)
          else
            $scope.requestForShare(cmisId)
        else
          $scope.requestForShare(cmisId)
      ,
        (rejectData)->
          $scope.requestForShare(cmisId)

      )
#      if true
#        $scope.requestForShare()
#      else
#        lang=localStorageService.get('language')
#        lang=Utils.getFullLang(lang)
#        previewUrl = window.cReaderUrl+'/pdf-preview/pdf-viewer?cmisId='+cmisId+'&fileName='+document.name+'&al='+lang
#        window.open(previewUrl)
      return false
    if $scope.project=='cpdf360'
      if document.contentStreamMimeType!='application/pdf'
        $translate('document_can_not_preview').then (text)->
          Utils.warning(text)
        return false
    if !Utils.canPreview(document)
      $translate('document_can_not_preview').then (text)->
        Utils.warning(text)
      return false
    cmisId=document.id
    if decodeURIComponent(document.id).indexOf(',')>-1
      cmisId=document.id
    else
      cmisId=document.id+','+document.versionLabel

    #  针对cpdf360 的预览
    #  https://jira.foxitsoftware.cn/browse/CPDF-3307
    #  https://cws-docker.connectedpdf.com/cpdfapi/v1/server/server-config "cReaderUrl": "https://beta-docker.connectedpdf.com/creader"
    #  https://beta-docker.connectedpdf.com/creader/pdf-preview/pdf-viewer?cmisId=79a32f0e-f14a-4294-aa7b-baece56a8636,1.0&fileName=f1118sj.pdf&al=zh-CN
    #  cpdf360 cDRM文件夹文档特殊处理
    if $scope.project=='cpdf360' && $scope.isSharedWithMe
      previewUrl = document.sharedLink
      window.open(previewUrl)
      return true
    if $scope.project=='cpdf360' && window.cReaderUrl
      console.log('project is : cpdf360')
      lang=localStorageService.get('language')
      lang=Utils.getFullLang(lang)
      previewUrl = window.cReaderUrl+'/pdf-preview/pdf-viewer?cmisId='+cmisId+'&fileName='+document.name+'&al='+lang
      window.open(previewUrl)
      return true
    # 其他项目的预览
    else
      console.log('==== normal preview')
      console.log('do not have window.cReaderUrl')
      Utils.showLoading($translate.instant('preview_loading_txt'))
      CmisServiceSession.getObject(document.id).ok (data)->
        $scope.choseFile = document
        document.previewPdf = null
        if window.viewDocument && typeof window.viewDocument == 'function'
          objectId = document.id
          downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true)
          indexUrl = ''
          fileName = document.name
          fileSize = document.contentStreamLength
          document.getRenditions ()->
            if document.renditions
              for rendition,i in document.renditions
                if rendition.kind == 'smx:linearized_pdf'
                  downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true, {streamId: rendition.streamId})
                else if rendition.kind == 'smx:linearized_index'
                  indexUrl = CmisServiceSession.getContentStreamURL(objectId, true, {streamId: rendition.streamId})

                #  phantom online use origin file instead linearized_pdf
                if CmisService.device == 'phantom-online' || CmisService.device == 'reader-online'
                  downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true)
                  if rendition.kind == 'smx:converted_pdf' && rendition.length == 0
                    Utils.closeLoading($translate.instant('preview_loading_txt'))
                    return Utils.warning($translate.instant('document_can_not_preview'))

                if rendition.kind == 'smx:converted_pdf' && rendition.length != 0
                  downloadUrl = CmisServiceSession.getContentStreamURL(objectId, true, {streamId: rendition.streamId})
            console.log(downloadUrl)
            window.viewDocument(objectId, downloadUrl, indexUrl, fileName, fileSize, '')
            console.log "call windown.viewDocument"
        else
          isAllowPreview = true
          document.getRenditions ()->
            Utils.closeLoading()
            if document.renditions
              console.log(document)
              for rendition,i in document.renditions
                if rendition.kind == 'smx:converted_pdf'
                  if rendition.length == 0
                    isAllowPreview = false
              if isAllowPreview
                $scope.pdfPreview(document)
              else
                $translate('document_can_not_preview').then (text)->
                  Utils.warning(text)
            else
              $scope.pdfPreview(document)
        Utils.sendGaEvent("File", "Preview", document.id)
        document.createActivity "view-document", {document_name: document.name, document_id: document.id}
      .notOk (r)->
        if Utils.handleCmis401Error(r)
          return
        jsonData = JSON.parse(r.text)
        console.log(jsonData);
        if jsonData.errorCode == '671'
          jsonData.message = jsonData.exception+ ' ' + jsonData.message;
        #          $rootScope.translateErrorMsg(jsonData)
        Utils.warning(jsonData.message)

##
#  dataType str 'cmis:lastModificationDate' 'cmis:creationDate' ...
#  dateInterval obj {after:'2016-12-13',before:'2016-12-16'}
#  property dateInterval.before can be null
##
  console.log ApiService
  getMineTypeValue = (obj,key)->
    if obj&&obj[key]
      return obj[key]
    else
      return '%'+key+'%'

  dateSql = (dataType,date)->
    # 传过来一个 日期格式 比如 2016-12-13
    # sql 只接受指定的 格式    2016-12-13T00:00:00
    #
    formatDate = ''
    dateKeymap = {
      lastModificationDateAfter:{
        cmisTag:'cmis:lastModificationDate'
        sign:'>='
      }
      lastAddedDateAfter:{
        cmisTag:'cmis:creationDate'
        sign:'>='
      }
  #      lastViewedDateAfter:{
  #        cmisTag:'cmis:lastModificationDate'
  #        sign:'>='
  #      }
    }
    if dataType == 'lastViewedDateAfter' || !dateKeymap[dataType]
      return ''

    formatDate = date+'T00:00:00'
#    timestamp
    sql = dateKeymap[dataType]['cmisTag'] + dateKeymap[dataType]['sign'] + " TIMESTAMP '"+ formatDate+"'"
    sql
  fileAddedBySql = (device)->
    map={
      fxt_mb_win:'Foxit MobilePDF for Windows'
      cloud_reading_web:'Cloud Reading Web'
      fxt_mb_ios:'Foxit MobilePDF for iOS'
      fxt_mb_and:'Foxit MobilePDF for Android'
      reader_mac:'Foxit Reader for Mac'
      reader_linux:'Foxit Reader for Linux'
    }
    if(!map[device])
      return ''
    #  select * from smxc:docWithSource WHERE smxc:addedBy='Foxit MobilePDF for Windows' AND IN_TREE('cc76b247-9834-4e4c-972a-668452bdb6c5')  必须类似这样的 sql 而非 cmis:document
    sql = "select * from smxc:docWithSource WHERE smxc:addedBy LIKE '"+map[device]+"' AND IN_TREE('"+$scope.tree[0]['id']+"')"
    sql

  fileMineTypeSql = (fileMineType)->
    # type of file
    mineTypeMap = {
      pdf:'application/pdf'
      zip:'application/zip | application/x-rar-compressed'
      image:'image%'
      text:'text%'
      ppt:'application/vnd.ms-powerpoint | application/vnd.openxmlformats-officedocument.presentationml.presentation'
      html:'text/html'
      video:'video%'
      excel:'application/vnd.ms-excel | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      word:'application/msword | application/vnd.openxmlformats-officedocument.wordprocessingml.document'
#      pptx:'application/vnd.openxmlformats-officedocument.presentationml.presentation'
#      xlsx:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
    multipleSql = getMineTypeValue(mineTypeMap,fileMineType).indexOf('|')
    sqlArr = []

    if multipleSql!= -1
#      Todo 写一个去除空格的函数 底下写成for 循环可能会有多个 值 传进来
      sqlArr[0]=getMineTypeValue(mineTypeMap,fileMineType).split('|')[0].slice(0,getMineTypeValue(mineTypeMap,fileMineType).split('|')[0].length-1)
      sqlArr[1]=getMineTypeValue(mineTypeMap,fileMineType).split('|')[1].slice(1)
#      console.log(sqlArr)
      sql = "(cmis:contentStreamMimeType LIKE '"+sqlArr[0]+"' OR cmis:contentStreamMimeType LIKE '"+sqlArr[1]+"')"
    else
      sql = "cmis:contentStreamMimeType LIKE '"+getMineTypeValue(mineTypeMap,fileMineType)+"'"
#    console.log sql
    sql
  fileTypeSql = (fileType)->
    # folder or file
    if fileType=='document'
      $scope.searchTypeSql = "SELECT * from cmis:document WHERE"
    else
      $scope.searchTypeSql = "SELECT * from cmis:folder WHERE"
  fileNameSql = (name)->
#    url 需要 decode
    sql = "cmis:name LIKE '%"+decodeURI(name)+"%'"
    sql
# above  把 字面量 翻译成 sql 语句

#  url para  a=b&c=d  => {a:b,c:d}
  urlParaToObj = (urlPara)->
    obj = {}
    if urlPara.indexOf('&')!=-1
      arr = urlPara.split('&')
      for i in arr
        obj[i.split('=')[0]]=i.split('=')[1]
    else
      obj[urlPara.split('=')[0]]=urlPara.split('=')[1]
    obj
  translateToSql = (key,value)->
    sql = ''
    if key.indexOf('Date')!=-1
      sql = dateSql(key,value)
    if key.indexOf('fileMineType')!=-1
      sql = fileMineTypeSql(value)
    if key.indexOf('title')!=-1
      sql = fileNameSql(value)
    if key.indexOf('fileAddedByDevice')!=-1
      sql = fileAddedBySql(value)
    if key.indexOf('type')!=-1
      fileTypeSql(value)
    sql

#    sql 前后缀
  adjustSql = (sqlSentence)->
    # 前缀 select * from cmis:document where
    # 后缀 IN_TREE()
    if($scope.searchTypeSql)
      prefix = $scope.searchTypeSql
    else
      prefix = 'SELECT * from cmis:document WHERE'
    suffix = "IN_TREE('"+$scope.tree[0]['id']+"')"
    sql = prefix+sqlSentence+suffix
    sql


  sqlSentences = (anchor)->
#    console.log anchor
    sentence = anchor.slice(anchor.lastIndexOf('/')+1)
    sentenceObj = urlParaToObj(sentence)
#    console.log('sentenceObj',sentenceObj)
    sql=' '

    for cmisTag,value of sentenceObj
      if translateToSql(cmisTag,value)
        sql=sql+translateToSql(cmisTag,value)+' AND '
    sql = adjustSql(sql)
#    console.log('sql',sql)
    return sql
  $scope.searchResult = []
  $scope.searchModeIsOn=false
  Utils.searchModeIsOn=false
  $scope.searchResult.name = ''
  if Utils.searchType then $scope.searchType = Utils.searchType else $scope.searchType= 'all'
  $scope.query={}
  $scope.query.str=''

  # chosenOptions remember last options
  $scope.chosenOptions=null
  $scope.advancedSearch = ()->
    modalInstance = $uibModal.open {
      animation: true,
      templateUrl: templatePath + "advanced-search.html",
      controller: 'advancedSearchModal'
      windowClass:'modal-opacity advaced-search-modal'
      resolve: {
        currentFolder: ()->
          $scope.currentFolder
        scope: ()->
          $scope
        searchModeIsOn: ()->
          $scope.searchModeIsOn
        chosenOptions: ()->
          $scope.chosenOptions
        location: ()->
          $location
        searchType: ()->
          $scope.searchType
      }
      backdrop: false
      appendTo: angular.element(document.getElementById('document-search-area'))
    }
    Utils.sendGaEvent('Search','Advanced','')
    modalInstance.result.then (chosenOptions)->
      $scope.chosenOptions=chosenOptions


  $scope.search = (title,type,query)->
    # type  folder document all_type
    # title keyword
    # query


#    console.log Utils
    if CmisService.isAndroid || CmisService.isIOS
      anchorPrefix = '/app/my'
    else
      anchorPrefix = ''
    if title&&title.length>0
      if Utils.sqlContainIllegalChar(title)
        $translate('contain_illegal_char').then((result)->
          Utils.warning(result)
        )
        return
    anchorBeforeChange = $location.url()
    $scope.searchModeIsOn=true
    Utils.searchModeIsOn=true
    if title||type
      query = 'title='+title+'&type='+type
      if type
        $scope.searchType = type
        Utils.searchType = type
    else
      queryObj = urlParaToObj(query)
#      console.log('queryObj',queryObj)

      # set type 'document' 'folder' 'all_type'
      if queryObj && queryObj['type']
        $scope.searchType = queryObj['type']
        Utils.searchType = queryObj['type']
      else
        $scope.searchType = 'document'
        Utils.searchType = 'document'
      # set search keyword
      if queryObj && queryObj['title']
        $scope.query.str = queryObj['title']
      else
        $scope.query.str = ''

    #    search 主要是为了 改变url
    console.log('search 方法里面的 searchType')
    console.log($scope.searchType)
    $location.path(anchorPrefix+'/search/'+query, false)
    anchor = anchorPrefix+'/search/'+query
    #    console.log('encodeURIComponent',encodeURIComponent(anchor))
    #    console.log('encodeURI',encodeURI(anchor))
    if encodeURI(anchor) == anchorBeforeChange
      Utils.loadingSearchResult = false
      $scope.loadingSearchResult = Utils.loadingSearchResult
    else
      Utils.loadingSearchResult = true
      $scope.loadingSearchResult = Utils.loadingSearchResult
    $timeout(()->
      $scope.$apply()
    ,0)
  window.CloudReading.search=$scope.search
  $scope.setSearchType = (query,type, e)->
    if e
      e.preventDefault()
      e.stopPropagation()
    console.log(type)
    if query&&query.length>0
      if Utils.sqlContainIllegalChar(query)
        $translate('contain_illegal_char').then((result)->
          Utils.warning(result)
        )
        return
    if !query
      query=''
    if !type
      $scope.searchType = 'all'
      Utils.searchType = 'all'
    else
      Utils.searchType = type
      $scope.searchType = type
    if $scope.searchType=='all'
      searchType='All'
    else if $scope.searchType=='document'
      searchType='File'
    else
      searchType='Folder'
    Utils.sendGaEvent(searchType,'Search','')


    #    $scope.searchType = type
    #    $location.path('/search?query='+query+'&type='+type, false)
    querySentence = 'title='+query+'&type='+type
    $scope.search(null,null,querySentence)
  $scope.cancelSearch = ()->
    if SelectMode.isOn
      $scope.cancelSelectMode()
    $scope.closeMobileSearchBar()
    $scope.searchModeIsOn=false
    Utils.searchModeIsOn=false
    $scope.query.str = ''
    $scope.searchResult = []
    $scope.searchResult.name = ''
    $scope.searchResult.allowableActions={}
    $scope.searchResult.allowableActions.canCreateDocument=false
    anchor = localStorageService.get 'lastAnchor'
    if anchor
      $location.path(anchor, false)
    else
      rootFolderAnchor = 'folder/'+Utils.rootFolder.id
      $location.path(rootFolderAnchor, false)
#      $scope.openFolder(Utils.rootFolder)

  getSearchResult=()->
    return $scope.searchResult
  window.CloudReading.cancelSearch=$scope.cancelSearch
  $scope.doActionFromAnchor = (anchor)->
    Utils.currentUrl = '#'+anchor
    if CmisService.isAndroid || CmisService.isIOS

      anchor = anchor.replace('/app/my','')
      anchorPrefix = '/app/my'
    else
      anchorPrefix = ''
    anchors = anchor.substr(1).split('/')

    if anchors[0] == 'folder'
      folderId = anchors[1]
      folder = ModelService.allFiles[folderId]
      if Utils.loadingSearchResult
        Utils.loadingSearchResult=false
        $scope.loadingSearchResult=Utils.loadingSearchResult
      if folder
        $scope.openFolder(folder)
      else
        $scope.openFolder(ModelService.tree[0])
    else if anchors[0] == 'file'
      fileId = anchors[1]
      document = ModelService.allFiles[fileId]
      if Utils.loadingSearchResult
        Utils.loadingSearchResult=false
        $scope.loadingSearchResult=Utils.loadingSearchResult
      if document
        parent = document.getParent()
        $scope.openFolder(parent)
        $scope.preview document
      else
        CmisServiceSession.getObject(fileId).ok (data)->
          document = ModelService.createDocument data
          parentPath = document.path.substr(0, document.path.lastIndexOf('/')).replace(/#/g, '%23')
          CmisServiceSession.getObjectByPath(parentPath).ok (data)->
            folderId = data.succinctProperties['cmis:objectId']
            folder = ModelService.allFiles[folderId]
            if folder
              $scope.openFolder(folder)
            $scope.choseFile = document
            #            $timeout ()->
            $scope.preview document
#            ,
#              1000
        .notOk (r)->
          if Utils.handleCmis401Error(r)
            return
          jsonData = JSON.parse(r.text)
          console.log(jsonData);
          #          $rootScope.translateErrorMsg(jsonData)
          Utils.warning(jsonData.message)
          #    for the search
    else if anchors[0] == 'search'
      console.log anchor
#      handle refresh
      index = anchor.lastIndexOf('/')
      urlPara = anchor.slice(index+1)
      urlObj = urlParaToObj(urlPara)
      Utils.searchType = urlObj && urlObj.type
      name = urlObj && decodeURI(urlObj.title)
      if !$scope.searchModeIsOn
        $scope.searchModeIsOn=true
        Utils.searchModeIsOn=true
      sql = sqlSentences(anchor)
      console.log('@@@@@@@')
      console.log(sql)
#      return false

      if Utils.searchType=='all'
        sqlForDoc = sql.replace('folder','document')
        sqlForFolder = sql.replace('document','folder')
        console.log('====sqlForDoc====')
        console.log(sqlForDoc)
        console.log('====sqlForFolder====')
        console.log(sqlForFolder)


        CmisServiceSession.query(sqlForFolder).ok((data)->
#        console.log(data)
#        console.log ModelService
          $scope.searchResult.name= 'search_result'
          $scope.searchResult.children = []
          $scope.folderTree=$scope.searchResult
          for file in data.results
            if !ModelService.allFiles[file['succinctProperties']['cmis:objectId']]
#              console.log('does not contain')
              if file['succinctProperties']['cmis:baseTypeId'] == 'cmis:folder'
                ModelService.createFolder(file)
              else
                ModelService.createDocument(file)
            $scope.searchResult.children.push(ModelService.allFiles[file['succinctProperties']['cmis:objectId']])
          CmisServiceSession.query(sqlForDoc).ok((data)->
            for file in data.results
              if !ModelService.allFiles[file['succinctProperties']['cmis:objectId']]
#                console.log('does not contain')
                if file['succinctProperties']['cmis:baseTypeId'] == 'cmis:folder'
                  ModelService.createFolder(file)
                else
                  ModelService.createDocument(file)
              $scope.searchResult.children.push(ModelService.allFiles[file['succinctProperties']['cmis:objectId']])
            Utils.loadingSearchResult=false
            $scope.loadingSearchResult=Utils.loadingSearchResult
            $scope.currentFolder=getSearchResult()
            if $scope.searchResult.length == 0
              $scope.choseFile = $scope.tree[0]
            $scope.showMobileMask=false
            $timeout(()->
              $scope.$apply()
            ,0)
          ).notOk((err)->
            if Utils.handleCmis401Error(err)
              return
            Utils.loadingSearchResult=false
            $scope.loadingSearchResult=Utils.loadingSearchResult
            Utils.warning(err)
          )
        ).notOk((err)->
          if Utils.handleCmis401Error(err)
            return
          Utils.loadingSearchResult=false
          $scope.loadingSearchResult=Utils.loadingSearchResult
          Utils.warning(err)
        )
      else
        sql = sqlSentences(anchor)
#        args1 = {
#          succinct:true
#          cmisaction:'query'
#          statement:sql
#          searchAllVersions:false
#        }

        callback = ()->
          $scope.currentFolder=$scope.searchResult
          $scope.loadingSearchResult=false
          Utils.loadingSearchResult=false
          if $scope.searchResult.length == 0
            $scope.choseFile = $scope.tree[0]
          $timeout(()->
            $scope.$apply()
          ,0)
#        Intersection = (arr1,arr2,arr3)->
##          return the common key
#          object = {}
#
#          object.arr1 = {
#            origin:arr1
#            len:arr1.length
#          }
#          object.arr2 = {
#            origin:arr2
#            len:arr2.length
#          }
#          object.arr3 = {
#            origin:arr3
#            len:arr3.length
#          }
#          if object.arr1.len>0 && object.arr2.len>0 && object.arr3.len>0
#            console.log('都不为0')
#
#          else
#            return []
#
#
#
#
#        needUsePhpApi = false
#        needSmxcSql = false
#        if anchor.indexOf('lastViewedDateAfter')>-1
#          needUsePhpApi = true
#
#        if anchor.indexOf('lastViewedDateAfter')>-1
#          sentence = anchor.slice(anchor.lastIndexOf('/')+1)
#          sentenceObj = urlParaToObj(sentence)
#          lastViewedDateAfterValue = sentenceObj['lastViewedDateAfter']
#          sqlOfSmxc = fileAddedBySql(lastViewedDateAfterValue)
#          if sqlOfSmxc
#            needSmxcSql = true
#            argsForSmxc = {
#              succinct:true
#              cmisaction:'query'
#              statement:sqlOfSmxc
#              searchAllVersions:false
#            }
#
#        $.when(ApiService.cmisSQL(args1),ApiService.cmisSQL(args))
#        .done((data1,data2,data3)->
#
#        ).fail(()->
#          console.log('yyy')
#        )
#
#        return false
        CmisServiceSession.query(sql).ok((data)->
          $scope.searchResult.name= 'search_result'
          $scope.searchResult.children = []
          $scope.folderTree=$scope.searchResult
          for file in data.results
            if !ModelService.allFiles[file['succinctProperties']['cmis:objectId']]
              console.log('does not contain')
              if file['succinctProperties']['cmis:baseTypeId'] == 'cmis:folder'
                ModelService.createFolder(file)
              else
                ModelService.createDocument(file)
            $scope.searchResult.children.push(ModelService.allFiles[file['succinctProperties']['cmis:objectId']])

          # lastViewedDateAfter 发起一次 php api 请求
          if(anchor.indexOf('lastViewedDateAfter')>-1)
            # 重新构成数组
            console.log()
            sentence = anchor.slice(anchor.lastIndexOf('/')+1)
            sentenceObj = urlParaToObj(sentence)
            date = sentenceObj.lastViewedDateAfter  # 2017-02-22

            currentDate = Utils.formatDate(new Date())
            console.log(currentDate)
            days = Utils.calculateDaysBetween(date,currentDate)+1
            if parseInt(days)<0
              $scope.searchResult.children = []
              callback()
              return false
            else
              $scope.searchResult.children = []
              ApiService.getRecentViewedFile(days,(data)->
                if data&&data.length
                  for id in data
                    if(ModelService.allFiles[id])
                      $scope.searchResult.children.push(ModelService.allFiles[id])
                  callback()
                else
                  callback()
              )
          else
            callback()
#          Utils.sendGaEvent('Document','Search',sql)
        ).notOk((err)->
          if Utils.handleCmis401Error(err)
            return
          $scope.loadingSearchResult=false
          Utils.loadingSearchResult=false
          Utils.warning(err)
        )
    else
#      url 未匹配的 跳到根目录
#      $location.url(anchorPrefix)
      $scope.openFolder(ModelService.tree[0])
      return
  $scope.openFolder = (folder,e)->
    e && e.stopPropagation()
    if $scope.searchModeIsOn
      $scope.cancelSearch()
    window.CloudReading.choseFile=null
    $scope.isFullScreenPreview = false
    $scope.multipleChooseFiles=[]
    $scope.multipleChooseFilesId=[]
    folder.getAces()
    if $scope.choseFile != folder && $(document.body) && $(document.body).width && $(document.body).width() > 1000
      $scope.choseFile = folder
      Utils.choseFile = folder
    folder.isExpand = true
    $scope.currentFolder = folder
    Utils.currentFolder = folder
    window.Utils =Utils
    if Utils.parentHasRenamed
      $timeout(()->
        Utils.parentHasRenamed=false
      ,1000*60*2)
      folder.refresh(()->
        parents = folder.getParents()
        for parent in parents
          parent.isExpand = true
        $timeout(()->
          $scope.$apply()
        )
      )
    else
      parents = folder.getParents()
      for parent in parents
        parent.isExpand = true

    if folder.path==decodeURIComponent(CmisService.path)+'/Shared With Me'
      console.log('====shared wuth me folder')
    if folder.loading
      return false
    $timeout(()->
      $scope.$apply()
    )
    folder.getRenditions()
    folder.loading = true
    folder.getChildren $scope, (obj)->
      $scope.$broadcast('get-children-ready')
      folder.loading = false
      $timeout(()->
        $scope.$apply()
      ,0)
      if window.foxitDriveLoaded
        window.foxitDriveLoaded()
    ,(errcallback)->
      folder.loading = false
      $timeout(()->
        $scope.$apply()
      )

  $scope.openSharedWithMeFolder=()->
    alert(123)
#  $scope.$on('get-children-ready',()->
#    folder.loading = false
#  )
  $scope.openFolderFormAnchor = (rootFolder)->
    anchor = $location.url()
#    console.log('openFolderFormAnchor',anchor)
    # check email is current user if not reset the localstorage
    userEmail = CmisService.email
    storedUserEmail = localStorageService.get 'userEmail'
    if !storedUserEmail || storedUserEmail != userEmail
      console.log('here')
      localStorageService.set "userEmail" , userEmail
      localStorageService.set "lastAnchor" , ''
      localStorageService.set "lastAnchorPath" , ''
    if anchor
      $scope.doActionFromAnchor(anchor)
      id = anchor.slice(anchor.lastIndexOf('/')+1)
      #          console.log(id)
      folder = ModelService.allFiles[id]
      #          console.log folder
      if folder
        localStorageService.set "lastAnchorPath" , folder.path
      else
        return
    else
      lastAnchor = localStorageService.get "lastAnchor"
      if CmisService.filePickerModal == "saveAs"
        lastAnchor = false
      if lastAnchor
        $scope.doActionFromAnchor(lastAnchor)
        id=lastAnchor.slice(lastAnchor.lastIndexOf('/')+1)
        console.log id
        folder = ModelService.allFiles[id]
        if folder
          localStorageService.set "lastAnchorPath" , folder.path
        else
          return
      else
        localStorageService.set "lastAnchorPath" , CmisService.path
        $scope.openFolder(rootFolder)


  $scope.refreshCurFolderList=()->
    console.log('====refresh====')
    if $scope.searchResult.name
#      Todo 暂时的处理方案 url 有点丑陋 后面在调整
      location.hash = location.hash+'&time='+Date.parse(new Date())/1000
      $scope.currentFolder.children = null
      $scope.currentFolder.loading=true
#      $scope.search null,null
      $scope.$broadcast 'scroll.refreshComplete'
      return
    $scope.currentFolder.loading=true
    $scope.clearSelection()
#    $timeout ->
##      $scope.currentFolder.folderList = []
#      $scope.currentFolder.children = null
#      $scope.currentFolder.loading=true
#      $scope.$apply()
#      return

    $scope.currentFolder.getChildren $scope, ((obj) ->
      $scope.multipleChooseFiles=[]
      $timeout (->
        $scope.$apply()
        return
      ), 0
      $scope.$broadcast 'scroll.refreshComplete'
      $scope.currentFolder.loading = false
      Utils.sendGaEvent('Folder','Refresh',$scope.currentFolder.id)
      return
    ), ((error) ->
      Utils.translateErrorMsg error.body
      $scope.$broadcast 'scroll.refreshComplete'
    ), true,true
    true
  window.CloudReading.$scope=$scope
  window.CloudReading.$timeout=$timeout
  window.CloudReading.refreshCurFolderList = $scope.refreshCurFolderList
  if CmisServiceSession && CmisServiceSession.defaultRepository
    $scope.progress = 100
    $scope.tree = ModelService.tree
    $scope.depth = 1
#    console.log $scope.tree
    $scope.openFolderFormAnchor()
  else
    checkSuccess = $timeout ()->
      $scope.serverError = true
    ,
      15000
    CmisServiceSession.loadRepositories().ok (res)->
      console.log('==loadRepositories==');
      console.log(res);
      if $scope.serverError
        return false
      $timeout.cancel(checkSuccess)
      CmisServiceSession.defaultRepository = res[CmisService.repository]
      localStorageService.set "rootFolderUrl" , res[CmisService.repository]['rootFolderUrl']
      $scope.progress = 50
      CmisServiceSession.getObjectByPath(CmisService.path, {includeAllowableActions:true}).ok (data)->
#      console.log('getObjectByPath',data)
        $scope.progress = 100

        cancel_file_checkout = localStorageService.get 'cancel-file-checkout'
        if cancel_file_checkout
          Utils.isUploadNewVersioning = false
          CmisService.session.cancelCheckOut(cancel_file_checkout).ok ()->
            localStorageService.set 'cancel-file-checkout', ''
          .notOk (r)->
            if Utils.handleCmis401Error(r)
              return
            localStorageService.set 'cancel-file-checkout', ''

        rootFolder = ModelService.createFolder data
        Utils.rootFolder = rootFolder
        ModelService.setRoot(rootFolder)
        $scope.tree = ModelService.tree
        $scope.depth = 1
        CmisServiceSession.getFolderTree(rootFolder.id, null, {includeAllowableActions:true}).ok (data)->
          rootFolder.folderList = ModelService.getChildrenFromData data
          # 默认打开 Reading/ConnectedPDF/cDRM 这个目录  https://jira.foxitsoftware.cn/browse/CPDF-3275
          cDRMFolderId=ModelService.allFilesPathIdMap[decodeURIComponent(CmisService.path+'/ConnectedPDF/cDRM')]
          if cDRMFolderId
            openFolder=ModelService.allFiles[cDRMFolderId]
          if openFolder && $scope.project=='cpdf360' # 除cpdf360其他项目的还是默认的Reading 目录
            $scope.openFolderFormAnchor(openFolder)
          else
            $scope.openFolderFormAnchor(rootFolder)
      .notOk (r)->
        if Utils.handleCmis401Error(r)
          return
        jsonData = JSON.parse(r.text)
        #        $rootScope.translateErrorMsg(jsonData)
        console.error(jsonData)
        emailFromPath =Utils.getEmailFromPath(CmisService.path)
        Utils.warning('无法查看文档，' + decodeURIComponent(emailFromPath) + ' 还没有上传过文档。')
#        Utils.warning(jsonData.message)

  $scope.sendViaEmail = (file)->
    if !file
      return false
    Utils.sendGaEvent("File", "SendEmail", file.id)
    if window.sendEmail
      if file.contentStreamLength < 20*1024*1024
        url = CmisServiceSession.getContentStreamURL(file.id,true)
        window.sendEmail(url,file.name)
      else
        $translate('document_too_big').then (text)->
          Utils.warning(text)

  $scope.getChildren = (folder)->
    #Loading return
    if $scope.loading
      return false
    $scope.multipleChooseFiles = []
    if $scope.choseFile != folder && $(document.body) && $(document.body).width && $(document.body).width() > 1000
      $scope.choseFile = folder
      $scope.choseFile.getAces()
#      $timeout ()-> $scope.$apply()

    folder.getRenditions()
    if $scope.currentFolder == folder
      folder.isExpand = !folder.isExpand
    else
      folder.isExpand = true
      $scope.currentFolder = folder

    $scope.loading = true
    folder.getChildren $scope, (obj)->
      $scope.$broadcast('get-children-ready')
#      $scope.children = folder.children
      $scope.loading = false

  $scope.chooseFileById = (id)->
    if $scope.choseFile.id == id || id == null
      return
    CmisServiceSession.getFolderParent(id).ok (data)->
      folder = ModelService.createFolder data
      $scope.chooseFileByPath(folder.path, id)
    .notOk (r)->
      if Utils.handleCmis401Error(r)
        return
      jsonData = JSON.parse(r.text)
      Utils.warning(jsonData.exception+': '+jsonData.message)

  $scope.chooseFileByPath = (path, id, folder = null)->
    if !folder?
      folder = ModelService.tree[0]
    nextPath = path.substr(folder.path.length).split('/')[1]
    folder.getChildren $scope, (obj)->
      if nextPath
        currentFolder = f for f in folder.children when f.name == nextPath
        currentFolder.isExpand = true
        $scope.chooseFileByPath(path, id, currentFolder)
      else
        $scope.currentFolder = folder
        currentFile = f for f in folder.children when f.id == id
        $scope.dbClick(folder)
        $scope.chooseFile(currentFile)
        folder.isExpand = true
  $scope.scopeApply = (time = 200)->
    Utils.rebound(
      'root-scope-apply',
      ()->
        $scope.$apply()
    ,
      time
    )
  $scope.isDbclick=false
  $scope.timerForClick = false
  $scope.click = (file,event)->
    if SelectMode.isOn
      $scope.chooseOrNot(file,event)
      return
    if event && event.button==2
      return
    if event
      event.stopPropagation()
    if $scope.isDbclick
      if $scope.pluginUi
        return 
      if $scope.timerForClick
        $scope.isDbclick = false
        $timeout.cancel($scope.timerForClick)
      $scope.dbClick(file)
    else
      $scope.isDbclick = true
      $scope.timerForClick= $timeout(()->
        $scope.chooseFile(file,event)
        $scope.isDbclick = false
      ,200)
  # show filedetail
#  if !$scope.pluginUi
#    $scope.detailPanelIsShow = true
#  else
#    $scope.detailPanelIsShow = false
  $scope.detailPanelIsShow =false
#  alert($scope.detailPanelIsShow)
  $scope.smallScreen=false
  adjustDetailPanel = ()->
    newValue = $(document).width()
    if newValue<700
      $scope.smallScreen=true
    else
      $scope.smallScreen=false
#    if newValue<=1000
#      $scope.closeFile()
#      $scope.showDetail()
  $timeout(()->
    adjustDetailPanel()
  ,399)

  # 尝试过使用 watch 但是 apply 滞后 相应太慢
  $timeout(()->
    adjustDetailPanel()
  ,399)

  window.onresize = ()->
    if !$scope.pluginUi
      adjustDetailPanel()
  $scope.switchDetailPanel=()->
    if !$scope.detailPanelIsShow
      if $scope.choseFile && $scope.choseFile.isDocument()
        Utils.sendGaEvent('Details','File','')
      else
        Utils.sendGaEvent('Details','Folder','')
    $scope.detailPanelIsShow = !$scope.detailPanelIsShow
  $scope.showDetail = ()->
    if !$scope.choseFile
      $scope.choseFile = $scope.currentFolder
    $scope.detailPanelIsShow = true
    if $scope.choseFile.isDocument()
      Utils.sendGaEvent('Details','File','')
    else
      Utils.sendGaEvent('Details','Folder','')

  $scope.closeFile = ()->
    $scope.detailPanelIsShow = false
  if !$scope.pluginUi
    adjustDetailPanel()
  # end filedetail

  $scope.disableMerge = false
  $scope.handleMergeOption = ()->
    if($scope.multipleChooseFiles.length>10)
      $scope.disableMerge=true
    else
      $scope.disableMerge=false
  #  如果没有 按 ctrl 或者 metakey  那么选择的话 就是单选
  $scope.fileMouseUp = (file,event)->
    if $scope.startTime&&event.which==1&&!event.metaKey&&!event.ctrlKey
      $scope.multipleChooseFiles=[]
      $scope.multipleChooseFilesId=[]
      $scope.multipleChooseFiles=[file]
      $scope.multipleChooseFilesId=[file.id]
      window.CloudReading.multipleChooseFiles = $scope.multipleChooseFiles
    $scope.startTime=false

#  $window.addEventListener('mousedown',(e)->
#  $('.fil-box')[0].addEventListener('mousedown',(e)->
#    if e && e.preventDefault
#      e.preventDefault()
#      e.stopPropagation
#  ,false)
  $scope.clearSelection=(e)->
    $('body').click()
    if $scope.noNeedClearSelection
      $scope.noNeedClearSelection=false
      return false
    if e && e.preventDefault
      e.preventDefault()
      e.stopPropagation
#    $scope.multipleChooseFiles=[]
#    $scope.multipleChooseFilesId=[]
#    $scope.choseFile=$scope.currentFolder
    $scope.chooseFile($scope.currentFolder)
    $timeout(()->
      $scope.$apply()
    ,0)


#  )
  window.CloudReading.clearSelection=$scope.clearSelection
  allFileCanShare = (files)->
    canShare=true
    for file in files
      if !file.isDocument()
        canShare=false
        break
    return canShare
  allFileCanSetPerm = (files)->
    canSetPerm=true
    for file in files
      if !file.isDocument()
        canSetPerm=false
        break
    return canSetPerm
  allFileCanMove = (files)->
    for file in files
      if file.isDocument()
        if file.allowableActions.canMoveObject==false
          return false
      else
        if file.readOnly==true
          return false
    return true
  allFileCanDelete = (files)->
    for file in files
      if file.isDocument()
        if file.allowableActions.canDeleteObject==false
          return false
      else
        if file.readOnly==true
          return false
    return true
  allFileCanDownload = (files)->
    for file in files
      if !file.isDocument()
        return false
      else
        if $scope.isSharedWithMe && file.description && file.description.canDownload!=1
          return false
    return true
  $scope.canDeleteMultipleFiles=false
  $scope.canMoveMultipleFiles=false
  $scope.canShareMultipleFiles=false
  $scope.canSetPermMultipleFiles=false
  $scope.chooseFile = (file,event,up,maintainContextMenu)->
    if(!maintainContextMenu)
      console.log('need close context menu ')
      $scope.$broadcast('closeContextMenu')
      $scope.$emit('closeContextMenu')
    console.log file
#    console.log ModelService.allFiles
    if event
      event.preventDefault()
      event.stopPropagation()
    if CmisService.device=='mobile'
      $scope.dbClick(file)
    if CmisService.pluginUi && !file.isDocument()
      $scope.dbClick(file)
    documentExistIndex =-1
    documentIdExistIndex =-1
    $scope.startTime=true
    if $scope.multipleChooseFiles && $scope.multipleChooseFiles.length
      documentExistIndex=$scope.multipleChooseFiles.indexOf(file)
    if $scope.multipleChooseFilesId && $scope.multipleChooseFilesId.length > 0
      documentIdExistIndex=$scope.multipleChooseFilesId.indexOf(file.id)
    $scope.choseFile = file if $scope.choseFile != file
    window.CloudReading.choseFile = $scope.choseFile
    file.getAces()
    if !file.renditions
      file.getRenditions(()->
        $timeout(()->
          $scope.$apply()
        )
      ,null,true)
    if file.isDocument()
      file.getVersions(null,(error)->
        $scope.translateErrorMsg(error.body)
      )
    #   handle cmd or ctrl click
    if event && event.metaKey || event && event.ctrlKey
      if $scope.fileSelectMode && $scope.fileSelectMode == 'single'
        return
      else
        if documentExistIndex==-1
          $scope.multipleChooseFiles.push(file)
          $scope.multipleChooseFilesId.push(file.id)
          $timeout(()->
            $scope.$apply()
          ,0)
          $scope.handleMergeOption()
  #        如果再一次点击取消选择
        else
          $scope.multipleChooseFiles.splice(documentExistIndex,1)
          $scope.multipleChooseFilesId.splice(documentExistIndex,1)
          $scope.choseFile = $scope.multipleChooseFiles[0] if $scope.multipleChooseFiles.length ==1
          $scope.choseFile = $scope.currentFolder if $scope.multipleChooseFiles.length ==0
          $scope.handleMergeOption()
          $timeout(()->
            $scope.$apply()
          ,0)

        window.CloudReading.multipleChooseFiles = $scope.multipleChooseFiles
#    handle single choose file
    else
      $scope.multipleChooseFiles=[]
      $scope.multipleChooseFilesId=[]
      $scope.multipleChooseFiles=[file]
      $scope.multipleChooseFilesId=[file.id]
      $scope.handleMergeOption()
      $timeout(()->
        $scope.$apply()
      ,0)
      window.CloudReading.multipleChooseFiles = $scope.multipleChooseFiles
    if $scope.multipleChooseFiles.length>1
      $scope.canDeleteMultipleFiles=allFileCanDelete($scope.multipleChooseFiles)
      $scope.canMoveMultipleFiles=allFileCanMove($scope.multipleChooseFiles)
      $scope.canShareMultipleFiles=allFileCanShare($scope.multipleChooseFiles)
      $scope.canSetPermMultipleFiles=allFileCanSetPerm($scope.multipleChooseFiles)
      $scope.canDownloadMultipleFiles=allFileCanDownload($scope.multipleChooseFiles)
  $scope.expandFolder= (folder, event)->
    folder.isExpand = !folder.isExpand
    event.stopPropagation()

  dbClickFn = (document,e)->
    if CmisService.isAndroid || CmisService.isIOS
      anchorPrefix = '/app/my'
    else
      anchorPrefix = ''
    if(e)
      e.stopPropagation()
    if document.isDocument()
#      $scope.preview(document)
      urlHashWillBe = '#/file/' + document.id
      #      console.log('Utils.currentUrl',Utils.currentUrl)
      #      console.log('urlHashWillBe ',urlHashWillBe)
      if Utils.currentUrl  && Utils.currentUrl != urlHashWillBe
        $location.path(anchorPrefix+'/file/' + document.id, false)
        parentFolder = document.getParent()
      else
        $scope.preview(document)
#      localStorageService.set "lastAnchorPath" , parentFolder.path
    else
#      $scope.getChildren(document)
      if !document.isExpand
        document.isExpand=true
      $scope.choseFile=document
      $scope.multipleChooseFiles=[]
      $scope.multipleChooseFilesId=[]
      Utils.sendGaEvent('Folder','Open','')
      localStorageService.set "lastAnchorPath" , document.path
      $location.path(anchorPrefix+'/folder/' + document.id, false)
      localStorageService.set "lastAnchor" , anchorPrefix+'/folder/' + document.id
  $scope.dbClick = (document,e)->
    if SelectMode.isOn
      return false
    if CmisService.device=='mobile'
      $timeout(()->
        if $scope.mobileShowInfo!=true
          dbClickFn(document,e)
        return false
      ,300)

    if $scope.filePickerModal=='retire' && document.isDocument()
      return false
    if $scope.filePickerModal=='saveAs' && document.isDocument() && !$scope.fromFillAndSign
      return false
    if $scope.filePickerModal=='saveAs' && document.isDocument() && $scope.fromFillAndSign
      console.log($scope.filePickerModal)
      if !document.isDocument()
        $scope.fillAndSign(document)
      return false
    dbClickFn(document,e)


  $scope.closePreview = (event)->
    if event
      event.stopPropagation()
    if CmisService.isIOS
      $cordovaStatusbar = $injector.get('$cordovaStatusbar')
      $cordovaStatusbar.show()
    page = 1
    if location.href.indexOf('localhost')==-1
      if window.top.previewFrame && previewFrame.window && previewFrame.window.getCurrentPage
        page = previewFrame.window.getCurrentPage()
    $http.post(CmisService.baseUrl + 'api/document/post-doc-preview-page?&access-token='+CmisService.token,{object_id:$scope.choseFile.id,page_number:page.currentPage})
    .success (data)->
      console.log(data)
    .error (error)->
      console.log(error)
    $scope.iframePdf = false
    $scope.isNormalFilePreview=false
    $scope.isFullScreenPreview = false
    $scope.previewUrl = ''
    if !CmisService.isAndroid && !CmisService.isIOS
      $location.path('/folder/' + $scope.currentFolder.id, false)



  $scope.deleteFolder = (folderForDel, event)->
#    if(ContextMenuService.menuElement)
#      ContextMenuService.close(ContextMenuService.menuElement)
    event && event.stopPropagation()
    $translate('folder_delete_confirm').then (text)->
      Utils.confirm text,'','','', (data)->
        parent = folderForDel.getParent()
        CmisServiceSession.deleteTree(folderForDel.id, true)
        .ok ()->
          if $scope.searchModeIsOn
            temperParent = $scope.currentFolder
            theIndex = j for tmp,j in temperParent.children when tmp.id == folderForDel.id
            if theIndex!=-1
              temperParent.children.splice(theIndex,1)
          folderListIndex = i for folder,i in parent.folderList when folderForDel.id == folder.id
          parent.folderList.splice(folderListIndex,1)
          index = i for folder,i in parent.children when folderForDel.id == folder.id
          if index!=-1
            parent.children.splice(index,1)
          $translate('delete_folder_success').then (text)->
            Utils.success text
          $scope.choseFile = $scope.currentFolder
          $scope.multipleChooseFiles=[]
          $scope.multipleChooseFilesId=[]
          $scope.cancelSelectMode(true)
          Utils.sendGaEvent("Folder", "Delete", folderForDel.id)
          parent.createActivity "delete-folder", {name: folderForDel.name,from_folder_name:parent.name, del_id:folderForDel.id}
        .notOk (r)->
          $scope.cancelSelectMode(true)
          if Utils.handleCmis401Error(r)
            return
          jsonData = JSON.parse(r.text)
          $scope.translateErrorMsg(jsonData)
      ,()->
        console.log('user cancelled ')

  $scope.delete = (document)->
#    console.log document
    $translate('file_delete_confirm').then (text)->
      Utils.confirm text,'','','', ()->
        CmisServiceSession.deleteObject(document.id, true)
        .ok ()->
          # need to handle search result delete update view
          parent = $scope.currentFolder
          if $scope.searchModeIsOn
            index = j for tmp,j in parent.children when tmp.id == document.id
            if index!=-1
              parent.children.splice(index,1)
          # absolute parent
          absolutePare = document.getParent()
          if absolutePare && absolutePare.children
            theIndex = i for tmp,i in absolutePare.children when tmp.id == document.id
            if theIndex!=-1
              absolutePare.children.splice(theIndex,1)
          $scope.choseFile = $scope.currentFolder
          $scope.multipleChooseFiles=[]
          $scope.multipleChooseFilesId=[]
          $translate('delete_file_success').then (text)->
            Utils.success text
          # delete fns file post   api/fns/delete-doc-from-cloud-reading?doc_id=dc40ee79-49ae-462d-9539-0dbebec72330%2C1.0&access-token=58f6c44fe4b0ada4aeb3c0a6%2Cww002%40mailinator.com
          postData = {
            doc_id:document.id
          }
          $.ajax({
            type: 'GET'
            url:CmisService.baseUrl+'api/fns/delete-doc-from-cloud-reading?doc_id='+document.id+'&access-token='+CmisService.token,
            beforeSend: (request)->
              request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
            success: (data)->
              console.log('====fns-delete====')
              console.log(data)
            error: (err)->
              console.log(err)
          })
          $scope.cancelSelectMode(true)
          Utils.sendGaEvent("File", "Delete", document.id)
          absolutePare.createActivity "delete-document", {name: document.name,from_folder_name:absolutePare.name, del_id:document.id}
        .notOk (r)->
          $scope.cancelSelectMode(true)
          if Utils.handleCmis401Error(r)
            return
          jsonData = JSON.parse(r.text)
          $scope.translateErrorMsg(jsonData)
  $scope.multipleDel=(event)->
#    ContextMenuService 就是 右键context的 服务 改写了原来的  js 库  把close 方法 放到了ContextMenuService上了 供我们使用
#    if(ContextMenuService.menuElement)
#      ContextMenuService.close(ContextMenuService.menuElement)
    #    不让他冒泡 选中的文件 就不会 变了
    Utils.sendGaEvent('FilesOrFolders','Delete','')
    event.stopPropagation()
    #    删去的总数是 知道的
    #    $('body').click()
    needSuccessCallBack=false
    $scope.tempMultiFiles=$scope.multipleChooseFiles
    $scope.multipleChooseFiles=$scope.tempMultiFiles
    $uibModal.open {
      animation: true,
      templateUrl: templatePath + "delete-confirm.html",
      controller: 'deleteModal'
      resolve: {
        files: ()->
          if $scope.multipleChooseFiles.length > 1
            $scope.multipleChooseFiles
          else
            [$scope.choseFile]
        currentFolder: ()->
          $scope.currentFolder
        needSuccessCallBack: ()->
          needSuccessCallBack
        scope: ()->
          $scope
        searchModeIsOn: ()->
          $scope.searchModeIsOn
      },
      backdrop: 'static'
    }
  downloadFuc = (document,versions,successfulCallback)->
    documentId=document.id
    if versions
      documentId=versions[0]['succinctProperties']['cmis:objectId']
    if window.downloadDocument && typeof window.downloadDocument == 'function'
      if CmisService.isAndroid || CmisService.isIOS
        downloadDocument(document)
      else
        downloadDocument(documentId)
      return false
    Utils.sendGaEvent("File", "Download", documentId)
    document.createActivity "download-document", {document_name: document.name, document_id: documentId}
    url = CmisServiceSession.getContentStreamURL(documentId, true)
    x=new XMLHttpRequest()
    x.open("GET", url, true)
    x.responseType = 'blob'
    x.setRequestHeader("Authorization", "Bearer " + CmisService.token)
    x.onload= ()->
      saveAs(x.response, document.name)
      successfulCallback && successfulCallback()
    x.send()
  $scope.download = (document)->
    if !CmisService.allowDownload
      Utils.warning('Document download not permitted')
      return
    $translate('downloading').then (text)->
      Loading.open text
    document.getVersions((versions)->
      console.log(versions)
      downloadFuc(document,versions,()->
        $timeout(()->
          Loading.close()
        ,0)
      )
    ,()->
      downloadFuc(document,null,()->
        $timeout(()->
          Loading.close()
        ,0)
      )
    ,true)
  $scope.multipleDownload=()->
    downloadFilesId=[]
    for file in $scope.multipleChooseFiles
      downloadFilesId.push(file.id)
    console.log(downloadFilesId)
    $translate('multiple_download',{total:downloadFilesId.length}).then (text)->
      Loading.open text
    ApiService.getCompressFileLink(downloadFilesId,()->
      Loading.close()
    ,null,$scope.multipleSelectModeOn)

  $scope.downloadVersion = (version)->
    if !CmisService.allowDownload
      Utils.warning('Document download not permitted')
      return
    if window.downloadDocument && typeof window.downloadDocument == 'function'
      if CmisService.isAndroid || CmisService.isIOS
        document = {}
        document.id = version.succinctProperties['cmis:objectId']
        document.name = version.succinctProperties['cmis:name']
        document.contentStreamLength = version.succinctProperties['cmis:contentStreamLength']
        downloadDocument(document)
      else
        downloadDocument(version.succinctProperties['cmis:objectId'])
      return false
    Utils.sendGaEvent("File", "DownloadVersion", version.succinctProperties['cmis:objectId'])
    $translate('downloading').then (text)->
      Loading.open text
    url = CmisServiceSession.getContentStreamURL(
      version.succinctProperties['cmis:objectId'],
      true
    )
    x=new XMLHttpRequest()
    x.open("GET", url, true)
    x.responseType = 'blob'
    x.setRequestHeader("Authorization", "Bearer " + CmisService.token)
    x.onload= ()->
      saveAs(x.response, version.succinctProperties['cmis:name'])
      Loading.close()
    x.send()

  $scope.upload = (files)->
    console.log(files)
    if !$scope.tempFolder
      $scope.tempFolder=$scope.currentFolder
    fileTooLarge = false
    maxFileSize = 30*1024*1024;
    if files.length
      if files.length==1
        if files[0].size > maxFileSize
          fileTooLarge = true
      else
        for file in files
          if file.size > maxFileSize
            fileTooLarge = true
            break
    if fileTooLarge
      if CmisService.device == 'phantom-online' # do not include 'reader-online'
        Utils.warning($translate.instant('phantom_limit_file_size'))
      else
        Utils.warning($translate.instant('file_too_big'))
#      return
    isIOS = CmisService.isIOS
    $('#upload-file').after $('#upload-file').clone().val('')
    $('#upload-file-for-cDRM').after $('#upload-file-for-cDRM').clone().val('')
    $('#upload-file-for-cDRM').remove()
    $('#upload-file').remove()
    if $scope.searchModeIsOn
      toastr.warning($translate.instant('search_result_can_not_upload'), $translate.instant('upload_failed'));
#      $uibModal.open {
#        animation: true,
#        templateUrl: templatePath + "user-not-allowed-upload.html",
#        controller: 'userNotAllowedUpload',
#        windowTopClass: 'not-allowed-window',
#        resolve: {
#          content:()->
#            $translate.instant('search_result_can_not_upload')
#        }
#      }
    else if !$scope.tempFolder.allowableActions || !$scope.tempFolder.allowableActions.canCreateDocument
      toastr.warning('', $translate.instant('upload_failed'));
#      $uibModal.open {
#        animation: true,
#        templateUrl: templatePath + "user-not-allowed-upload.html",
#        controller: 'userNotAllowedUpload',
#        windowTopClass: 'not-allowed-window',
#        resolve: {
#          content:()->
#            ''
#        }
#      }
    else
      if files == null
        return false
      results = []
      i = 0
      j = 0
      len = files.length
      while j < len
        file = files[j]
        #fix ios all upload file has same name
        if isIOS and file.name.indexOf('image.') > -1
          i++
          date = file.lastModifiedDate
          year = date.getFullYear()
          month = if date.getMonth() + 1 > 9 then date.getMonth() + 1 else '0' + date.getMonth() + 1
          day = if date.getDate() > 9 then date.getDate() else '0' + date.getDate()
          hour = if date.getHours() > 9 then date.getHours() else '0' + date.getHours()
          minute = if date.getMinutes() > 9 then date.getMinutes() else '0' + date.getMinutes()
          second = if date.getSeconds() + i > 9 then date.getSeconds() + i else '0' + date.getSeconds() + i
          extName = Utils.getFileExt(file.name)
          fileNameForIos = '' + year + '-' + month + '-' + day + '-' + hour + minute + second + '.' + extName
          file.iosName = fileNameForIos
        #console.log('ios name rename')
        #console.log(fileNameForIos)
        #console.log(file)
        if !Utils.isAllowExtension(file)
          $translate('file_type_error', allowExtensions: CmisService.allowExtension.join(', ')).then (text) ->
            Utils.warning text
            return
          j++
          continue
        if file.size < maxFileSize
          results.push UploadQueue.add(file, $scope.tempFolder.id, {
            'cmis:name': if isIOS and file.name.indexOf('image.') > -1 then file.iosName else file.name
            'cmis:objectTypeId': 'cmis:document'
          }, null, (newCmisFile,notSetPermission)->
            if $scope.currentFolder.isCDRMFolder()
            # setPermission 转换完成的文档才有 newCmisFile
              if newCmisFile && !notSetPermission
                console.log(Utils.templateData)
                if Utils.templateData
                  if Utils.templateData.userList && Utils.templateData.userList.length>0
                    postData={
                      "cDocID": newCmisFile.cDocId
                      "fileLink": "",
                      "notice": "0",
                      "invitation": "0",
                      "userList": Utils.templateData.userList
                    }
                    ApiService.setCdrmPermission(postData,(data)->
                      console.log(data)
                      Utils.success('上传并成功的设置了权限')
                    ,()->
                      Utils.success('上传成功 权限设置失败')
                    )
                  else
                    Utils.success('上传成功')
                else
                  ApiService.getProtectTemplate(()->
                    console.log('q')
                  ,()->
                    console.log('s')
                  )
                  postData={
                    "cDocID": newCmisFile.cDocId
                    "fileLink": "",
                    "notice": "0",
                    "invitation": "0",
                    "userList": [
                      {
                        "userEmail": ""
                        "isGroup": 0,
                        "everyone": 0,
                        "permitType": 3,
                        "emailDomain": Utils.getEmailDomainFrom(CmisService.email)
                        "permission": [
                          0
                        ],
                        "offlineDays": 0,
                        "deviceLimit": 0,
                        "onlineDate": "",
                        "fullControl": 0,
                        "offline": 0,
                        "online": 0,
                        "onlineDays": 0,
                        "accessPages": {
                          "isAccessPages": 0,
                          "wrapperContent": "",
                          "wrapperPic": "",
                          "Pages": []
                        }
                      }
                    ]
                  }
            $timeout(
              ()->
                $scope.$apply()
            ,0
            )
          )
        j++
  Utils.openUploadFilePicker=$scope.openUploadFilePicker



  $scope.$on 'set-file-cDRM-permission', (event, file)->
    console.log('==== set-file-cDRM-permission')
    console.log(event)
    console.log(file)
    $scope.setFileCDRMPerm(file,false)
  ###
  setFileCDRMPerm
  drop file  setFileCDRMPerm(null,true,null,pdfFiles)
  查看当前模版 setFileCDRMPerm(null,true,$event,null,true)
  右键上传    setFileCDRMPerm(null,true)
  文档右键    setFileCDRMPerm(file,false)
  ###
  $scope.setFileCDRMPerm=(newCmisFile,useDefaultProtectTemplate,e,dropFiles,justShowTemplate)->

    # useDefaultProtectTemplate 默认保护模版
    if justShowTemplate
      title=$translate.instant('当前保护模板设置')
    else if dropFiles || useDefaultProtectTemplate
      title=$translate.instant('上传文档权限设置')
    else
      title=$translate.instant('当前文档权限设置')
    # cpdf360 cDRM文件夹
    if $scope.currentFolder.isCDRMFolder()
      console.log('====setFileCDRMPerm')
      if !justShowTemplate
        justShowTemplate=false
      Utils.showLoading()
      if !useDefaultProtectTemplate
        cmisId=newCmisFile.id
        if decodeURIComponent(newCmisFile.id).indexOf(',')>-1
          cmisId=newCmisFile.id
        else
          cmisId=newCmisFile.id+','+newCmisFile.versionLabel

        promiseArr=[ApiService.getUserList(),ApiService.getCDocInfoByCmisId(cmisId),ApiService.getUserInputList('@')]
        $q.all(promiseArr).then((arr)->
          console.log('=====promiseArr aaaaa data')
          console.log(arr)
          userListArr=arr[0]
          data = arr[1]
          emailList=arr[2]
          console.log(emailList)
          newCmisFile.cDocId=data.data.cDocID
          if data && data.data && data.data.cDocID
            newCmisFile.cDocId=data.data.cDocID
          console.log('=====newCmisFile')
          console.log(newCmisFile)
          $timeout(()->
            Utils.closeLoading()
          ,300)
          Utils.modalInstance = $uibModal.open {
            animation: true,
            templateUrl: templatePath + "set-cDRM-permission-new.html",
            controller: 'setCDRMPermCtrlNew'
            windowClass:'cDrm-permission-modal'
            size:'lg'
            resolve: {
              title: ()->
                title
              userListArr: ()->
                userListArr
              emailList: ()->
                emailList
              userData: ()->
                data
              parentScope: ()->
                $scope
              file: ()->
                newCmisFile
              defaultProtectTemplate: ()->
                false
              dropFiles: ()->
                dropFiles
              justShowTemplate: ()->
                justShowTemplate
            },
            backdrop: 'static'
          }
        ,()->
          $timeout(()->
            Utils.closeLoading()
          ,300)
          Utils.warning('稍后在试')
        )
      else
        promiseArr=[ApiService.getUserList(),ApiService.getProtectTemplate(),ApiService.getUserInputList('@')]
        $q.all(promiseArr).then((arr)->
          console.log('=====promiseArr bbbb data')
          console.log(arr)
          userListArr=arr[0]
          data = arr[1]
          emailList=arr[2] # user input
          console.log(emailList)
          $timeout(()->
            Utils.closeLoading()
          ,300)
          Utils.modalInstance = $uibModal.open {
            animation: true,
            templateUrl: templatePath + "set-cDRM-permission-new.html",
            controller: 'setCDRMPermCtrlNew'
            windowClass:'cDrm-permission-modal'
            size:'lg'
            resolve: {
              title: ()->
                title
              userListArr: ()->
                userListArr
              emailList: ()->
                emailList
              userData: ()->
                data.data && data.data.length>0 && data.data[0] || null
              parentScope: ()->
                $scope
              file: ()->
                newCmisFile
              defaultProtectTemplate: ()->
                true
              dropFiles: ()->
                dropFiles
              justShowTemplate: ()->
                justShowTemplate
            },
            backdrop: 'static'
          }
        ,()->
          $timeout(()->
            Utils.closeLoading()
          ,300)
          Utils.warning('稍后在试')
        )
    else
      # 非cDRM文件夹 直接打开文件选择框
      if $scope.project=='cpdf360'
        Utils.warning($translate.instant('only_support_upload_in_cDRM'))
      else
        $scope.openUploadFilePicker($scope.currentFolder)

  $scope.safeApply = (expr)->
    try
      return $scope.$eval(expr)
    catch e
      console.log e
    finally
      $scope.$root.$digest

  # uploadNewVersion 上传新版本
  $scope.openModifyFilePicker = (file)->
    $scope.tempFile = file
    isAndroid = CmisService.isAndroid
    if isAndroid
      $scope.createDocumentInAndroid(true)
    else
      $timeout ()->
        $scope.noNeedClearSelection=true
        $('#modify-file').click()
      ,0
  $scope.openUploadFilePicker = (folder, dropFile = null)->
    if !folder
      folder = $scope.currentFolder
    if CmisService.isDrmRoom
      $uibModal.open {
        animation: true,
        templateUrl: templatePath + "upload-drn-file.html",
        controller: 'UploadDrnCtrl'
        resolve: {
          dropFile: ()->
            dropFile
          folder: ()->
            folder
          parentScope: ()->
            $scope
        },
        backdrop: 'static'
      }
    else
      $scope.tempFolder = folder
      isAndroid = CmisService.isAndroid
      if $scope.currentFolder.isCDRMFolder()
        document.getElementById('upload-file-for-cDRM').click()
      else
        document.getElementById('upload-file').click()

  $scope.createDocumentInAndroid = (isModify)->
    success =  (data)->
      file = {
        filepath:data.filepath,
        name:data.name,
        size:data.size,
        type:data.type,
      }
      files = new Array(file)
      if isModify
        $scope.modifyFile(file)
      else
        $scope.upload(files)

    errorFunction = (msg)->
      $translate('UPLOAD_FILE_ERROR_ANDROID').then (text)->
        Utils.warning(text)
    filechooser.open({},success, errorFunction)

  $scope.setContentStream=(file)->
    # file  input select file
    # cmisFile ModelService file object
    $scope.noNeedClearSelection=false
    okFunction = (checkInObj)->
      Utils.isUploadNewVersioning = false
      Utils.sendGaEvent("File", "UploadNewVersion", $scope.tempFile.id)
      $scope.tempFile.createActivity "upload-version", {document_name: $scope.tempFile.name, document_id: $scope.tempFile.id}
      $scope.tempFile.getVersions ()->
        Loading.close()
        $('#modify-file').val('')
        $scope.choseFile = $scope.tempFile
        #          refresh 并不会更新 id 导致后续的bug refresh 已经改了 会更新id
        $scope.tempFile.refresh(()->
          $scope.choseFile.getRenditions(null,null,true)
          $scope.multipleChooseFiles=[]
          $scope.multipleChooseFilesId=[]
          $scope.multipleChooseFiles=[$scope.choseFile]
          $scope.multipleChooseFilesId=[$scope.choseFile.id]
        )
        $translate('upload_succ').then (text)->
          Utils.success text
        $timeout ()-> $scope.$apply()
      , null , true

    notOkFunction = (r)->
      if Utils.handleCmis401Error(r)
        return
      Utils.isUploadNewVersioning = false
      jsonData = JSON.parse(r.text)
      Loading.close()
      $('#modify-file').val('')
      Utils.warning(jsonData.message)
    if CmisService.isAndroid
      filePath = encodeURI(file.filepath)
      # for android
      console.log 'file://' + filePath
      window.resolveLocalFileSystemURL 'file://' + filePath, ((fileEntry) ->
        console.log fileEntry
        fileEntry.file (localfile) ->
          reader = undefined
          reader = new FileReader

          reader.onloadend = (fileReadResult) ->
            data = undefined
            data = new Uint8Array(fileReadResult.target.result)
            fileBlobData = new Blob([ data ], type: file.type)
            CmisServiceSession.setContentStream($scope.tempFile.id,fileBlobData,true,{},null)
            .ok(okFunction).notOk(notOkFunction)
          reader.readAsArrayBuffer localfile
      ), (error) ->
        console.log error
    else
      reader = undefined
      reader = new FileReader
      reader.onloadend = (fileReadResult) ->
        data = undefined
        data = new Uint8Array(fileReadResult.target.result)
        fileBlobData = new Blob([ data ], type: file.type)
        CmisServiceSession.setContentStream($scope.tempFile.id,fileBlobData,true,{},null)
        .ok(okFunction).notOk(notOkFunction)
      reader.readAsArrayBuffer file

  $scope.checkIn = (file)->

    okFunction = (checkInObj)->
      Utils.isUploadNewVersioning = false
      Utils.sendGaEvent("File", "UploadNewVersion", $scope.tempFile.id)
      $scope.tempFile.createActivity "upload-version", {document_name: $scope.tempFile.name, document_id: $scope.tempFile.id}
      $scope.tempFile.getVersions ()->
        Utils.isUploadNewVersioning = false
        Loading.close()
        $('#modify-file').val('')
        $scope.choseFile = $scope.tempFile
        #          refresh 并不会更新 id 导致后续的bug refresh 已经改了 会更新id
        $scope.tempFile.refresh(()->
          $scope.choseFile.getRenditions(null,null,true)
          $scope.multipleChooseFiles=[]
          $scope.multipleChooseFilesId=[]
          $scope.multipleChooseFiles=[$scope.choseFile]
          $scope.multipleChooseFilesId=[$scope.choseFile.id]
        )

        $translate('upload_succ').then (text)->
          Utils.success text
        $timeout ()-> $scope.$apply()
      , null , true

    notOkFunction = (r)->
      if Utils.handleCmis401Error(r)
        return
      Utils.isUploadNewVersioning = false
      jsonData = JSON.parse(r.text)
      Loading.close()
      $('#modify-file').val('')
      Utils.warning(jsonData.message)

    if CmisService.isAndroid
      filePath = encodeURI(file.filepath)
      # for android
      console.log 'file://' + filePath
      window.resolveLocalFileSystemURL 'file://' + filePath, ((fileEntry) ->
        console.log fileEntry
        fileEntry.file (localfile) ->
          reader = undefined
          reader = new FileReader

          reader.onloadend = (fileReadResult) ->
            data = undefined
            data = new Uint8Array(fileReadResult.target.result)
            fileBolbData = new Blob([ data ], type: file.type)

            CmisServiceSession.checkIn($scope.tempFile.id, true, null, fileBolbData)
            .ok(okFunction).notOk(notOkFunction)

          reader.readAsArrayBuffer localfile
      ), (error) ->
        console.log error
    else
      CmisServiceSession.checkIn(
        $scope.tempFile.id,
        true,
        null,
        file
      ).ok(okFunction).notOk(notOkFunction)

  loadMoreChildren=()->
    if $scope.currentFolder.loadMoreChildren
      $scope.currentFolder.loadMoreChildren($scope,
        ()->
          $timeout(()->
            $scope.currentFolder.loadingMoreChildren=false
            console.log($scope.currentFolder)
            $scope.$apply()
          )
        ()->
          $timeout(()->
            $scope.currentFolder.loadingMoreChildren=false
            console.log($scope.currentFolder)
            $scope.$apply()
          )
      )

  $scope.loadMoreChildren = ()->
    if $scope.currentFolder.baseTypeId && $scope.currentFolder.baseTypeId == 'cmis:folder'
#    loadMoreChildren()
      Utils.rebound('loadingMoreChildren',loadMoreChildren,300)
  $scope.modifyFile = (file)->
    # file 是input 里面的file 对象
    $('#modify-file').after($('#modify-file').clone().val(""))
    $('#modify-file').remove()
    $scope.noNeedClearSelection=false
    if !file?
      return false
    fileTooLarge = false
    maxFileSize = 30*1024*1024;
    if file.size > maxFileSize
      fileTooLarge = true
    if fileTooLarge
      if CmisService.device == 'phantom-online' # do not include 'reader-online'
        Utils.warning($translate.instant('phantom_limit_file_size'))
      else
        Utils.warning($translate.instant('file_too_big'))
      return
    Utils.isUploadNewVersioning = true;
    console.log(Utils.isUploadNewVersioning);
    $scope.modifyNewFile = file
#    $scope.checkIn(file)
#        if new version of the file has different name then pop up a confirm window
    if $scope.choseFile.name!=file.name
      $translate('update_with_new_name').then (text)->
        $uibModal.open {
          animation: true,
          templateUrl: templatePath + "confirm.html",
          controller: 'uploadNewVersionCtrl'
          windowClass:'modal-opacity'
          resolve: {
            parentScope: ()->
              $scope
            rootScope:()->
              $scope
            content:()->
              text
          },
          backdrop: 'static'
        }
#     same name then upload
    else
      $translate('uploading').then (text)->
        if $scope.progressHandler
          $scope.progressHandler.dismiss()
          UploadQueue.modal=false
        Loading.open text
      $scope.setContentStream($scope.modifyNewFile)



#      if $scope.tempFile.isVersionSeriesCheckedOut
#        $scope.checkIn(file)
#      else
#        CmisServiceSession.checkOut($scope.tempFile.id).ok (checkOutObj)->
#          $scope.checkIn(file)
#        .notOk (r)->
#          if Utils.handleCmis401Error(r)
#            return
#          Loading.close()
#          jsonData = JSON.parse(r.text)
#          Utils.warning(jsonData.message)



  $scope.rename = (file)->
#   当执行该方法  必须立马把choose file 切换到当前的文件上
    $scope.choseFile = file
    modalInstance=$uibModal.open {
      animation: true,
      templateUrl: templatePath + "rename.html",
      controller: 'RenameCtrl',
      windowClass:'modal-opacity'
      resolve:{
        file: ()->
          file
        scope: ()->
          $scope
      },
      backdrop: 'static'
    }
    modalInstance.result.then((file)->
      console.log('=======afterrenamefile')
      console.log(file)
      ApiService.syncCmisFileNameToCdrm(file)
    ,()->
      console.log('dismiss')
    )

  $scope.invite = (document = null) ->
#    console.log CmisService.membershipType
    $scope.isOwner=CmisService.membershipType=='Owner'
    if !$scope.isOwner
      $scope.sendToOwner='Send Request to Room Owner'
    else
      $scope.sendToOwner='Send Invitation Email'
    $scope.sending=false
    $uibModal.open ({
      animation: true,
      templateUrl: templatePath + "invite-model.html",
      controller: "createInviteModal",
      resolve:{
        document:()->
          document
        sendToOwner:()->
          $scope.sendToOwner
        sending:()->
          $scope.sending
        isOwner:()->
          $scope.isOwner
      },
      backdrop: 'static'
    })
  $scope.updateLeftAsideFolderTree = ()->
    return false
    temperTree = ModelService.tree
    $scope.tree = []
    $timeout(()->
      $scope.$apply()
    ,0)
    $timeout(()->
      $scope.tree = temperTree
    ,0)


  $scope.createFolder = ()->
    modalInstance = $uibModal.open {
      animation: true,
      templateUrl: templatePath + "create-folder.html",
      controller: 'CreateFolderCtrl',
      windowClass:'modal-opacity',
      backdrop: 'static'
    }
    modalInstance.result.then (folderName)->
      if folderName.length==0
        $translate('folder_name_null',).then (text)->
          Utils.warning(text)
        return
      url = CmisServiceSession.defaultRepository.rootFolderUrl+'?objectId='+$scope.currentFolder.id
      postData = {
        'cmisaction': 'createFolder'
        'propertyId[0]':'cmis:name'
        'propertyValue[0]': folderName
        'propertyId[1]' : 'cmis:objectTypeId'
        'propertyValue[1]': 'cmis:folder'
        succinct:true
        includeAllowableActions:true
      }
      $.ajax(
        {
          type: 'POST'
          url:url,
          beforeSend: (request)->
            request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
          data: postData
          success: (object)->
#            $scope.updateLeftAsideFolderTree()
            folder = ModelService.createFolder object
            if !$scope.currentFolder.folderList
              $scope.currentFolder.folderList=[]
            if !$scope.currentFolder.children
              $scope.currentFolder.children=[]
            $scope.currentFolder.folderList.push(folder)
            $scope.currentFolder.children.push(folder)
            $timeout(()->
              $scope.$apply()
            ,0)
            Utils.sendGaEvent "Folder", "Create", folder.id
            folder.createActivity "create-folder", {name:folder.name, to_folder_name:$scope.currentFolder.name}
          error: (r)->
            console.log(r.responseJSON)
            $scope.translateErrorMsg(r.responseJSON,{name:folderName})
        }
      )
  $scope.moveTo = (waitMoveFile,event)->
    #    ContextMenuService 就是 右键context的 服务 改写了原来的  js 库  把close 方法 放到了ContextMenuService上了 供我们使用
#    if(ContextMenuService.menuElement)
#      ContextMenuService.close(ContextMenuService.menuElement)
    #    不让他冒泡 选中的文件 就不会 变了
    event && event.stopPropagation()
    if waitMoveFile
      waitMoveFile.hasMoved=true
    if $scope.multipleChooseFiles && $scope.multipleChooseFiles.length>0
      for file in $scope.multipleChooseFiles
        file.hasMoved=true
    modalInstance = $uibModal.open {
      animation: true,
      templateUrl: templatePath + "move-to-folder.html",
      controller: 'moveToFolderModal'
      windowClass:'modal-opacity'
      resolve: {
        files: ()->
          if $scope.multipleChooseFiles.length > 0
            $scope.multipleChooseFiles
          else
            [waitMoveFiles]
        currentFolder: ()->
          $scope.currentFolder
        scope: ()->
          $scope
      },
      backdrop: 'static'
    }
  $scope.openPrivateFolder=()->
    privateFolderId=ModelService.allFilesPathIdMap[decodeURIComponent(CmisService.path+'/ConnectedPDF/cDRM/Private')]
    if !privateFolderId
      return
    privateFolder=ModelService.allFiles[privateFolderId]
    if privateFolder
      $scope.openFolder(privateFolder)
  $scope.opencDRMFolder=()->
    cDRMFolderId=ModelService.allFilesPathIdMap[decodeURIComponent(CmisService.path+'/ConnectedPDF/cDRM')]
    if !cDRMFolderId
      return
    cDRMFolder=ModelService.allFiles[cDRMFolderId]
    if cDRMFolder
      $scope.openFolder(cDRMFolder)
  moveToPrivateSuccess=(objectId, sourceFolder, targetFolder,lastErr)->
    if !lastErr
      $scope.successMoveCount++
    file=ModelService.allFiles[objectId]
    if $scope.successMoveCount + $scope.failedMoveCount == $scope.totalMovedItemNum
      if $scope.successMoveCount == 1
        $translate('succ_move_private',{fileName:file.name}).then((result)->
          Utils.success(result)
        )
    if lastErr
      return false
    else
      file = ModelService.getObjectById(objectId)
      file.refresh()
      if !file.isDocument()
        if currentFolder.id == sourceFolder.id
          sourceFolder=currentFolder
        if sourceFolder.folderList&&sourceFolder.folderList.length
          index = i for folder,i in sourceFolder.folderList when file.id == folder.id
          sourceFolder.folderList.splice(index,1)
        #              和下面同样的问题 空文件夹 移入的时候会报错
        if !targetFolder.folderList
          targetFolder.folderList=[]
        targetFolder.folderList.push file

        file.loadChildren = false
        file.folderList = null
        file.children = []
        Utils.sendGaEvent("Folder", "Move", file.id)
        file.createActivity "move-folder", {name: file.name, from_folder_name: sourceFolder.name, to_folder_name: targetFolder.name}
      else
        Utils.sendGaEvent("File", "Move", file.id)
        file.createActivity "move-document", {name: file.name, from_folder_name: sourceFolder.name, to_folder_name: targetFolder.name}

      index = i for folder,i in sourceFolder.children when file.id == folder.id
      sourceFolder.children.splice(index,1)
      #            新创建的文件夹 移入文件会报错
      if !targetFolder.children
        targetFolder.children=[]
      targetFolder.children.push(file)
      $scope.multipleChooseFiles=[]
      $scope.choseFile=$scope.currentFolder
      $scope.scopeApply(500)

  moveToPrivate = (objectId,sourceFolder,destFolder)->
    targetFolder=destFolder
    targetId = destFolder.id
#    sourceId = sourceFolder.id
    sourceId = ModelService.getObjectById(objectId).getParent().id
    options = {}
    options.objectId = objectId
    options.cmisaction = 'move'
    options.targetFolderId = targetId
    options.sourceFolderId = sourceId
    $.ajax(
      {
        type: 'POST'
        url:CmisService.session.defaultRepository.rootFolderUrl,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: options
        success: ()->
          moveToPrivateSuccess(objectId, sourceFolder, targetFolder)
        error: (r)->
          $scope.failedMoveCount++
          if $scope.failedMoveCount+$scope.successMoveCount==$scope.totalMovedItemNum
            moveToPrivateSuccess(objectId, sourceFolder, targetFolder,true)
          path = ModelService.allFiles[targetId].path + '/' + ModelService.allFiles[objectId].name
          console.log(r.responseJSON)
          Utils.translateErrorMsg(r.responseJSON, {
            path: path
          })
      }
    )
  $scope.moveToPrivateFolder=()->
    files=$scope.multipleChooseFiles
    $scope.totalMovedItemNum = files.length
    $scope.successMoveCount = 0
    $scope.failedMoveCount = 0
    privateFolderId=ModelService.allFilesPathIdMap[decodeURIComponent(CmisService.path+'/ConnectedPDF/cDRM/Private')]
    console.log(files)
    console.log(privateFolderId)
    if !privateFolderId
      return
    delay=0
    for file in files
      fileId=file.id
      sourceFolder=file.getParent()
      destFolder=ModelService.getObjectById(privateFolderId)
      setTimeout((fileId,sourceFolder,destFolder )->
        moveToPrivate(fileId,sourceFolder,destFolder)
      ,delay*2000,fileId,sourceFolder,destFolder)
      delay++

  $scope.commentContent=''
  $scope.postComment = (content)->
    $scope.choseFile.postComment(content)
    this.commentContent=''

  $scope.openCloudArchive = ()->
    if window.openCloudArchive && typeof window.openCloudArchive == 'function'
      window.openCloudArchive()
  #handle drag and drop a file event.
  $scope.$on 'file-dropzone-drop-event', (event, files)->
    $scope.tempFolder = $scope.currentFolder
    if $scope.currentFolder.isCDRMFolder()
      pdfFiles=[]
      for file in files
        if !Utils.isPdf(file)
          $translate('file_type_error', {allowExtensions:'PDF'}).then (text)->
            Utils.warning(text)
        else
          pdfFiles.push(file)
      if pdfFiles.length>0
        $scope.setFileCDRMPerm(null,true,null,pdfFiles)
    else
      if $scope.project=='cpdf360'
        Utils.warning($translate.instant('only_support_upload_in_cDRM'))
      else
        $scope.upload(files)

  $scope.requestForShare=(file)->
    modalInstance=$uibModal.open {
      animation: true,
      templateUrl: templatePath + "request-share-confirm.html",
      controller: 'requestShareModal'
      windowClass:'modal-opacity'
      resolve: {
        file: ()->
          file
        scope: ()->
          $scope
      },
      backdrop: 'static'
    }
  window.CloudReading.requestForShare=$scope.requestForShare
  $scope.fillAndSign = (file,id,event)->
#    console.log 'fillNSign',file
#    console.log CmisService.baseUrl
#    console.log CmisService.baseUrl+'fns/fill-forms-pdf-view?id=1&docId='+file.id
#    console.log window
#    console.log window.top
    if file
      if(file.isDocument())
        if event.data && event.data.eventName=='openFileFromAchive'
          # only support for fillableform
          console.log(event.data)
          if file.contentStreamMimeType!='application/pdf'
            $translate('not_support_this_type').then (text)->
              Utils.warning(text)
            return false
          else
            docId = file.id
            window.top.postMessage(docId,'*')
        else
          if !Utils.canPreview(file)
            $translate('not_support_this_type').then (text)->
              Utils.warning(text)
            return false
          # pdf 类型 直接传id
          if file.contentStreamMimeType == 'application/pdf'
            docId = file.id
            docUrl = CmisServiceSession.getContentStreamURL(docId, true)
          # 非pdf 类型 看是否转换成功 成功传 rendition streamId 失败提示 不能
  #          console.log(docUrl)
  #          console.log(CmisService.baseUrl+'fns/fill-forms-pdf-view?id=1&docId='+docId)
  #          expect docUrl like https://cloud-docker.connectedpdf.com/cmis/browser/fxcld/root?succinct=true…nt&objectId=f9257948-c852-437c-bfb6-7b5853064634%2C2.0&download=attachment
  #          expect url https://cloud-docker.connectedpdf.com/fns/fill-forms-pdf-view?id=1&docId=f9257948-c852-437c-bfb6-7b5853064634,2.0
            window.top.postMessage({
              id:docId
              eventName:'passIdFromFoxitDrive'
            },'*')
  #            window.top.location.href=CmisService.baseUrl+'fns/fill-forms-pdf-view?fromCloudReading=1&docId='+docId
          else
            file.getRenditions ()->
              if file.renditions
                for rendition,i in file.renditions
                  if rendition.kind == 'smx:converted_pdf' && rendition.length!=0
                    docId = rendition.streamId
                    docUrl = CmisServiceSession.getContentStreamURL(docId, true, {streamId: rendition.streamId})
              if docId
                # expext docUrl https://cloud-docker.connectedpdf.com/cmis/browser/fxcld/root?succinct=true&token=5872fa19e4b07a512a38b3c6%2Cww002%40mailinator.com&streamId=5924fafa-19ba-420f-989c-4dac683d4307%2C1.0-cvtpdf-rdtion&cmisselector=content&objectId=5924fafa-19ba-420f-989c-4dac683d4307%2C1.0-cvtpdf-rdtion&download=attachment
                # expect https://cloud-docker.connectedpdf.com/fns/fill-forms-pdf-view?id=1&docId=5924fafa-19ba-420f-989c-4dac683d4307,1.0-cvtpdf-rdtion
                window.top.postMessage({
                  id:docId
                  eventName:'passIdFromFoxitDrive'
                },'*')
  #                window.top.location.href=CmisService.baseUrl+'fns/fill-forms-pdf-view?fromCloudReading=1&docId='+docId
              else
                $translate('not_support_this_type').then (text)->
                  Utils.warning(text)
      else
        #  本项目作为 iframe的时候  外部调用 iframe 里面的方法很慢
#        $scope.dbClick(file)
        # 直接 替换hash
        window.location.hash='folder/'+file.id

    else
      $translate('no_file_selected').then (text)->
        Utils.warning(text)
      if id
        # 传id 代表的是 从 fill and sign 页面直接预览 是可以预览的
        location.href=CmisService.baseUrl+'fns/fill-forms-pdf-view?&fromCloudReading=1&docId='+id
  window.addEventListener('message', (event)->
    console.log('message')
    console.log(event.data)
    if event && event.data && event.data.eventName
      if event.data.eventName=='openFileFromFillAndSign' || event.data.eventName=='openFileFromAchive'
        if ~event.origin.indexOf(CmisService.baseUrl)
          $scope.fillAndSign(window.CloudReading.choseFile,null,event)
        else
          return
    else
      return
  )
  window.fillAndSign=$scope.fillAndSign
  if window.foxitDriveLoaded
    url = window.location.href
    window.foxitDriveLoaded(url)
#    // UNKNOWN : -1,
#    //            PDFTOCPDF : 0,
#    //            IMGTOPDF : 1,
#    //            OPTIMIZER : 2,
#    //            WATERMARK : 3,
#    //            MERGEPDF : 4,
#    //            PDFTOTXT : 5,
#    //            PDFTOIMG : 6,
#    //            PDFPROTECT : 7,
#    //            PDFREDACTOR : 8,
#    //            PDFHEADERFOOTER : 9,
#    //            ROTATEPDF : 10,
#    //            PDFTOWORD : 11,
#    //            SPLITPDF : 12,
#    //            PAGEORGANIZER : 13,
#    //            PDFTOEXCEL : 14,
#    //            PDFTOHTML : 15,
#    //            WORDTOPDF : 16,
#    //            PDFFLATTEN   : 17,
#    //            EXCELTOPDF : 18,
#    //            PPTTOPDF : 19,
#    //            Text2PDF : 20,
#    //            HTML2PDF : 21,
#    //            PDFTOPPT : 22,
#    //            PREVIEWPDF : 23
#                  EXPORTALLIMG : 24
  toolsMap={
    PDFTOCPDF : 'PDF To CPDF',
    IMGTOPDF : 'Image To PDF',
    OPTIMIZER : 'Compress PDF',
    WATERMARK : 'Watermark',
    MERGEPDF : 'Merge PDF',
    PDFTOTXT : 'PDF To Text',
    PDFTOIMG : 'PDF To Image',
    PDFPROTECT : 'PDF Password Protect',
    PDFREDACTOR : 'Redact PDF',
    PDFHEADERFOOTER : 'PDF Header and Footer',
    ROTATEPDF : 'Rotate PDF',
    PDFTOWORD : 'PDF To Word',
    SPLITPDF : 'Split PDF',
    PAGEORGANIZER : 'PDF Page Organizer',
    PDFTOEXCEL : 'PDF To Excel',
    PDFTOHTML : 'PDF To HTML',
    WORDTOPDF : 'Word To PDF',
    PDFFLATTEN   : 'PDF Flattern',
    EXCELTOPDF : 'Excel To PDF',
    PPTTOPDF : 'PowerPoint To PDF',
    Text2PDF : 'Text To PDF',
    HTML2PDF : 'HTML To PDF',
    PDFTOPPT : 'PDF To PowerPoint',
    PREVIEWPDF : 'Preview PDF',
    EXPORTALLIMG : 'Export All Images'
  }
  $scope.convertPdfTo=(type,file)->
    # file.minetype must be pdf
    $scope.closePanelInPanel()
    if window.convertPdfTo
      Utils.sendGaEvent('','Document '+toolsMap[type],'')
      window.convertPdfTo(type,file)
  $scope.export_all_image=(file)->
    $scope.closePanelInPanel()
    if window.convertPdfTo
      window.convertPdfTo(type,file)
      Utils.sendGaEvent('','Document '+toolsMap[type],'')
  $scope.compress_PDF=(type,file)->
    $scope.closePanelInPanel()
    if window.convertPdfTo
      window.compress_PDF(type,file)
      Utils.sendGaEvent('','Document '+toolsMap[type],'')
  $scope.organizePDF=(type,file)->
    $scope.closePanelInPanel()
    if window.organizePDF
      window.organizePDF(type,file)
      Utils.sendGaEvent('','Document '+toolsMap[type],'')
  $scope.protectPdf=(type,file)->
    $scope.closePanelInPanel()
    if window.protectPdf
      window.protectPdf(type,file)
      Utils.sendGaEvent('','Document '+toolsMap[type],'')
  $scope.showDropDownMenu=(scope)->

    console.log(scope)

  $scope.showContextmenu=(docId)->
    element=$('[data-id='+docId+']')[0]
    if window.CustomEvent
      element.dispatchEvent(new CustomEvent('contextmenu'))
    else if document.createEvent
      ev = document.createEvent('HTMLEvents')
      ev.initEvent('contextmenu', true, false)
      element.dispatchEvent(ev)
    else
      element.fireEvent('oncontextmenu')
  $scope.itemOnTouchEnd=(docId)->
    console.log(docId)

  $scope.hasSelections = ->
    SelectMode.multipleChooseFiles.length > 0

  $scope.multipleSelectModeOn = false

  $scope.toggleSelectMode = (e) ->
    console.log e
    console.log SelectMode
    SelectMode.isOn = true
#    for file in $scope.multipleChooseFiles
#      file.isSelected=true
    $scope.tempChoseFile = $scope.choseFile
    $scope.tempMutipleChooseFiles = $scope.multipleChooseFiles
    $scope.tempMutipleChooseFilesId = $scope.multipleChooseFilesId
    $scope.multipleSelectModeOn = true
    $scope.multipleChooseFiles = []
    $scope.multipleChooseFilesId = []
    console.log 'now changeSelectMode'

  $scope.cancelSelectMode =(needRestore)->
    console.log SelectMode
    SelectMode.closeSelectMode()
    if !needRestore
      $scope.multipleChooseFilesId = $scope.tempMutipleChooseFilesId
      $scope.multipleChooseFiles = $scope.tempMutipleChooseFiles
    $scope.multipleSelectModeOn = false
    SelectMode.isOn = false
  window.CloudReading.ModelService = ModelService
  if CmisService.hideRetireNotify
    # phantom online 由phantom online自己展示
    $scope.hideRetireNotify=true
  $scope.closeRetireNotify = ()->
    $scope.hideRetireNotify=true
  $scope.chooseOrNot = (file, e) ->
    file.isSelected = !file.isSelected
    if file.isSelected
      SelectMode.add file
    else
      SelectMode['delete'] file
    if $scope.multipleChooseFiles.length>1
      $scope.canDeleteMultipleFiles=allFileCanDelete($scope.multipleChooseFiles)
      $scope.canMoveMultipleFiles=allFileCanMove($scope.multipleChooseFiles)
      $scope.canShareMultipleFiles=allFileCanShare($scope.multipleChooseFiles)
      $scope.canSetPermMultipleFiles=allFileCanSetPerm($scope.multipleChooseFiles)
      $scope.canDownloadMultipleFiles=allFileCanDownload($scope.multipleChooseFiles)
    $scope.multipleChooseFiles=SelectMode.multipleChooseFiles
    $scope.multipleChooseFilesId=SelectMode.multipleChooseFilesId
    window.CloudReading.multipleChooseFiles = $scope.multipleChooseFiles
    $scope.choseFile=$scope.multipleChooseFiles[0]
    console.log SelectMode
    console.log($scope.multipleChooseFiles)
    console.log($scope.currentFolder)
    e && e.stopPropagation()
    e && e.preventDefault()
